public interface iUserInfo
{
string getUserName(int userId);
string getUserAge(string username);
}
public class UserDb implements iUserInfo
{
string getUserName(int userId)
{
//code to retrieve user info from the database
}
}
public class UserTxtFile implements iUserInfo
{
string getUserName(int userId)
{
//code to retrieve user info from the plain text file
}
}
public class UserManager()
{
private iUserInfo userInfo;
public string retrieveUserData(string userName)
{
return userInfo.getUserAge(userName);
}
}
My professor says
"the above user manager class has a reference variable of type iUserInfo, so, if this reference is provided by a factory method or by any other means, the code of the manager class will be the same regardless of what implementation is provided.
This approach maximizes flexibilty if some implementations need to be altered during the process of software development, as higher level layers will not be affected at all."
There are two things I need to understand; the flexibility maximization and the factory method.
The latter I guess it may be something like this
public class UserManager()
{
private iUserInfo userInfo;
private UserTxtFile uTxtFile;
private UserDb uDB;
public iUserInfo GetUserInfoObjFactory(bool dbOrTxt)
{
return dbOrTxt? uTxtFile:uDB;
}
public string retrieveUserData(string userName)
{
return userInfo.getUserAge(userName);
}
}
and during the lecture I was sort of daydreaming about other things, and now can't figure out what that exactly means ? I would love to understand a little more in depth, just in case some interviewers may attack me with more open questions that I am unsure of how to answer.
Could you also add some code that will break the above source in an example case when the high level layers are affected ? Thank you a lot.
[Update] I also find an answer such as "we need Interface to group common methods" is not really convincing. An Abstract base class alone does help too. For example, a Fly behavior from 2 objects {Penguin vs Bird}. I can't simply tell the interviewer that IFly is needed at all. Even when I have millions of different objects which need Fly, then I can always implement each Fly for each of them. Because I still need to do that in the implementing classes even when I design the IFly. Would you please offer more detail cases or re-explain how interface becomes a must ?