Java: guidelines for inheriting factory methods from base classes

I am creating a set of classes to represent various data in an old database. Instead of using exceptions inside the constructors to signal errors, I decided to use factory methods to create different objects. However, I am trying to figure out how best to use some of these factories when inheriting from these classes. I'm looking for a conceptual explanation (that is: best practices say what you should do ...) is not so much a code example (although code examples are always welcome).

For example, suppose I have a User class with the createUser factory method. I also have another class called Employee that extends the User class. How can I reuse (that is: call) all the code of the createUser method from the createEmployee method so that it fills all the Employees fields that are inherited from the User class?

An obvious “work around” would be to change the Employee class to use the User class instead of extending it, but this is not consistent with normal OO principles.

+3
source share
3 answers

initializeUser (User user), . createUser initializeUser. createEmployer initializeEmployer, initializeUser, Employer.

, initalize , . , factory, .

+1

, , , .

, : " ", Employee - "".

- getUser getEmployee.

getEmployee Employee, . , .

DAO (Data Access Object), , . , UserDAO EmployeeDAO.

UserDAO , User EmployeeDAO, EmployeeDAO - :

Employee getEmployee(String id) {
  Employee emp = new Employee();
  User u = UserDAO.getUser(id);
  // either populate values or pass in the Employee since it can be a User class, to be populated.
  // get employee values
  return emp;
}

. , Employee, , .

.

0

, , . init() , (, init() Employee -). Factory, User ( ), - . createInstance(insert params here) , init() , . , ( init()), , , .

:

class User() {
    //... your fields and constructor here

    public void init() {
       //... do your User init here
    }
}

class Employee extends User {
    ...
    public void init() {
       super.init();
       // ... other init stuff if you want
    }
}

class UserFactory{
    // ...

    public User createInstance(UserType type, String name, ...) {
        User user;
        switch (type) {
            case UserType.EMPLOYEE: user = new Employee(name,...);
        //... your other cases here
        }

        // the important part
        user.init();
        return user;
    }
}

0
source

All Articles