I have two different types of users, and I have mapped them to the two Java classes UserWheel and UserSea , and they have a common abstract superclass of the User class . The data stored for these types of users is about the same, but the behavior is different.
Then I created an abstract class called UserCollection with derived classes UserWheelCollection and UserSeaCollection to find subordinates or load subusers.
Then I added an abstract method to the UserCollection class with a signature
public abstract List<User> listAllSubusers()
this is because the implementation will be different. Each Created User will be UserWheel or UserSea, depending on which method was called, but also the rest of the implementation is different.
Then I want to add a new method to UserCollection with the signature public UserloadById (int idUser) . In this case, the implementation will be the same, except for the fact that the returned user will be an instance of either UserWheel or UserSea . In this case, I am reluctant to use the abstract method in the base class due to code duplication.
I can test a specific UserCollection class with instanceof and create a corresponding subclass, but it does not look object oriented and violates the open-close principle.
- createNewUser() UserCollection , createNewUser().
, ? - ?
UPDATE. :
abstract class User
public String getAddress()
public void setAddress()
...
class UserSea extends User
class UserWheel extends User
abstract class UserCollection
protected abstract User createNewUser();
public abstract List<User> listAllSubUsers();
public User loadById(int idUser) {
User newUser = createNewUser();
return newUser;
}
class UserSeaCollection
protected User createNewUser() {
return new UserSea();
}
public List<User> listAllSubusers()
class UserWheelCollection
protected User createNewUser() {
return new UserWheel();
}
public List<User> listAllSubusers()
, trashgod, :
interface SubuserManagement
List<User> listAllSubUsers();
...
interface UserCrud
void create();
User readById(int idUser);
void update();
void delete();
class UserSeaCollection implements SubUserManagement, UserCrud
private SubUserManagement subuserBehavior = new SubUserManagementSeaImplementation();
private UserCrud userCrudBehavior = new UserCrud();
void create {
subUserBehavior.create();
}
...
class UserWheelCollection implements SubUserManagement, UserCrud
...
class SubUserManagementWheelImplementation implements SubUserManagement
List<User> listAllSubUsers();
class SubUserManagementSeaImplementation implements SubUserManagement
List<User> listAllSubUsers();
class UserCrudImplementation implements UserCrud //only 1 implementation
void create();
User readById(int idUser);
void update();
void delete();
UserCollectionWheel UserCollectionSea, , . .
UserCollectionWheel UserCollectionSea , , . :
UserCollection userColl = new UserCollection();
userColl.setSubUserBehavior(new SubUserManagementSeaImplementation());
userColl.setCrudBehavior(new UserCrud());
, . ? ?
2: , .