我有一个以下类共享同一个" 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();
或者是否有适合此类问题的更好的设计模式?
答案 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()
成为public
,static
函数并在实例化任何子类之前调用它:
Client.buildStateFromArgs(args);
UserClient client = new UserClient();
...