mercredi 1 avril 2015

Creating and managing unique instances of class in Java that can be accessed by different users

I have a programming problem that I want to know if it can be solved using Java design techniques. I have class Service and I have a class Client. A client requests a service and if it's not already existing, then it will be created (i.e. new service object). If the service has been created (i.e by a different client or even the same client), then the Service class will not create a new object. Instead, the client can be added to the service (if not already added). Other fields and methods of the Service class will be applied to clients of the same service.



public class Service {

private String service;
private ArrayList<Integer> clients;
//.... other field

public Service (String s){
this.service = s;
clients = new ArrayList<>;
}

public void addClient(int c){
clients.add(c);
}



//..other methods

}

public class Client {

private int clientID;
private ArrayList<String> services;

public Client(int id){
clientID = id;
services = new ArrayList<>;
}

public void addService(String s){
services.add(s);
}

public void requestService() {
for(int i=0; i<services.size();i++)
Service s = new Service(services.get(i));
}

}


The problem with the above approach is that new service objects with the same service would be created by different clients.


I'm currently reading up on on static factory. As far as my research goes:



public class Service(){

private Service(){
}

public static Service createService(String service){
if (/*service doesn't exist*/)
return new Serivce();
else
return null;
}
//....
}


This above code would prevent creating a new object instance. However, if service already exists and therefore returns null, then a new client cannot join (or use) that particular service.


Aucun commentaire:

Enregistrer un commentaire