Java从父对象实例化子对象

时间:2017-10-30 02:34:33

标签: java design-patterns

我有一个以下类共享同一个" state"并执行CRUD操作。此操作不可重复/幂等。

public class Client {
    private static String state;
    public Client(args){
        this.state = buildStateFromArgs();  // this value will not change
    }

    public void createUser();
    public User getUser();
    public User updateUser();
    public void deleteUser();

    public void createJob();
    public Job getJob();
    public Job updateJob();
    public void deleteJob();

    // other CRUD functions ....
}

我正在考虑将其重构为类似

的内容
public class Client {
    public Client(args){
        this.state = buildStateFromArgs();
    }
    private static String state;
}

public class UserClient extends Client{
    public void createUser();
    public User getUser();
    public User updateUser();
    public void deleteUser();
}

但我不确定实施儿童班的最佳方法是什么。假设这是当前的实现,

Client client = new Client(args);
client.createUser();
client.createJob();

我应该只是垂头丧气吗?

Client client = new Client(args);
UserClient userClient = (UserClient) client;
userClient.createUser();
JobClient jobClient = (JobClient) client;
jobClient.createJob();

或者我应该从父母那里构建孩子?

Client client = new Client(args);
UserClient userClient = new UserClient(client);
userClient.createUser();
JobClient jobClient = new JobClient(client);
jobClient.createJob();

或者是否有适合此类问题的更好的设计模式?

1 个答案:

答案 0 :(得分:1)

鉴于UserClient 是-a Client,我会采用以下方法:

UserClient client = new UserClient();
client.createUser();

我采用这种方法的原因是用户特定的功能应该仅存在于UserClient上,因此只能从这种功能中调用。

鉴于必须在所有客户端共享state的新信息,我可能会使用静态初始化程序:

class Client {
    private static String state;
    static {
        state = buildStateFromArgs(args);  // this value will not change
    }
}

这假定此点args可用。如果不是,那么您需要使buildStateFromArgs()成为publicstatic函数并在实例化任何子类之前调用​​它:

Client.buildStateFromArgs(args);
UserClient client = new UserClient();
...