Initialize a singleton by configure file is suitable or not?
I notice that the constructor of singleton should not have any parameter, the reason is that if you need use parameters to configure your object, probably that should not be singleton. Seems this sentence very famous, but indeed there are serval cases are special:
e.g.
We design a simple distributed system to deal with tons of users' query:
- only one central server
- n sub servers, each sub server connecting to central server
- there is no connections between sub servers
Obviously, we may design the "central server" as singleton, the details like this:
- enum ServerType;
- abstract class Server;
- class CentralServer inherit from Server;(CentralServer is singleton)
- class SubServer inherit from Server;
- class Query;
- ... ... ...
But the central server need some configuration, such as:
- serverName
- description
- portNum-ipAddress map
- the list of its sub servers
- the size of BlockingQueue
- ... ... ...
How to initialize the central server by these properties?
My current solution:
- using the configure file to finish this part job.
- I define another class called
Configuration
.
So the current constructor of central server like this:
class CentralServer extends Server implements Runnable, ....... {
....
....
private static CentralServer _instance;
private CentralServer () {
super();
....
serverName = Configuration.getCentralServerName();
description = Configuration.getCentralServerDescription();
Configuration.initCentralServerPortNumIpMap(portNumIpMap);
Configuration.initCentralServerSubServersList(subServersList);
sizeBlockingQueue = Configuration.initCentralServerBlockingQueueSize();
....
}
public CentralServer getInstance() {
if (_instance == null) {
_instance = new CentralServer();
}
return _instance;
}
....
....
}
The Configuration class, will read and analyze configuration-file, to get out of configuration info.
My Question:
Initialize singleton like this suitable or not, if not, please give out more suitable approach
I also need configure all sub servers, so seems the Configuration class is too heavy, should I split the Big Configuration class into two sub class? class CentralConfiguration, and class SubConfiguration?