Premises
Before angry hearts start blaming the singleton pattern and related practices, or criticizing this matter with theoretical crusades, I state that the question represents a real issue in the real life, analysed by people with a bit of brain and common sense.
Also, before technical answers and comments start to raise up, I specify that it is not a matter of implementation. My library does it well according to the rules of engagement and I am not looking for different possible solutions.
Question
Managing UI components, there are some which need to be unique.
For example, a dialog window, which has to be accessed and used by other different components for their own purpose of informing the user or proposing some options or interaction.
Dialog needs its own configuration settings which must be provided at the instantiation time, like for example the CSS classes to recognize which option button is pressed, handlers for specific events such as minimize, maximize, close and so on.
var options = {
confirmOption: '.confirm-btn',
cancelOption: '.cancel-btn',
maximize: function(dialog) {
$('.long-message').show();
}
};
If it was a normal class allowing multiple instances, in line with a spread and consistent syntax, I would do:
var dialog = new Dialog(options);
As the Dialog
class is a singleton, the instantiation with the new
keyword throws an error as it is logic to expect, while the proper getInstance
method has to be used:
var dialog = Dialog.getInstance();
As options should be passed at the construction time, the syntax becomes:
var dialog = Dialog.getInstance(options);
and I know many will turn up the nose, while purists may say that it does not depict an immutable class, as getting the instance with or without arguments will get into something different.
My point is that:
- getting several instances, the object returned is always the same, apart of the internal properties the first instantiation may set;
- getting an instance after the first time, possible arguments passed to
getInstance
are ignored, as internal members have already been set, saving possible overwriting of settings which must be immutable; - internal members of the class which do not affect the consistency of the object, may be edited through proper methods.
What is your point regarding this situation?
Would you accept such syntax?
If not, which syntax would you use, trying to produce readable code, to respect the singleton constraint and the possibility to set config settings?