Is there any
Interface To class design pattern.
Currently I'm joining a new company.and their design pattern is
"Interface to Class " Design pattern.
But I don't know any Interface to class design pattern...
Have anyone using Interface to class design pattern...
Interface To class is commonly used pattern specially in JAVA/Spring-Boot as it supports the concept of loosely coupling.In this pattern,
Below is the simple code to demonstrate the interface to class pattern.
public interface UserMethod {
User getUser();
boolean saveUser(User user);
}
Now create an implementation class for it.
public class UserDatabase implements UserMethod{
@Override
public User getUser() {
//Do your logic for getting user
}
@Override
public boolean saveUser(User user) {
//Do logic to save user
}
}
public class MongoUserDatabase implements UserMethod {
@Override
public User getUser(String id) {
// MongoDB query to get user
}
@Override
public boolean saveUser(User user) {
// MongoDB operation to save user
}
}
public class UserService {
private final UserMethod userMethod;
public UserService(UserMethod userMethod) {
this.userMethod = userMethod;
}
public User getUser(String id) {
return userMethod.getUser(id);
}
public boolean saveUser(User user) {
return userMethod.saveUser(user);
}
}
UserMethod userMethod = new UserDatabase();
UserService userService = new UserService(userMethod);
// After migration
UserMethod userMethod = new MongoUserDatabase();
UserService userService = new UserService(userMethod);
Notice:as in above we created constructor of Interface not implementation class. What are it's advantages: