dimanche 29 octobre 2017

Java instantiating child object from parent object

I have a following class that shares the same "state" and performs CRUD actions.

public class Client {
    private 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 ....
}

I am thinking of refactoring it to something like

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

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

But I am not sure what is the best approach to instatiate the child class. Suppose this is the current implementation,

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

Should I simply just downcast?

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

Or should I construct the child from parent?

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

Or is there a better design pattern suited for this kind of problem?

Aucun commentaire:

Enregistrer un commentaire