I am curious to see the two approach to address the scenario where we just want one shared state across an application.
Singleton: You create a class where it has a scope instance as a class member and you have to create threadsafe getter and creator to build the singleton instance
Package/Model Loading: You can simply define and instantiate a state data in the package as a variable during the init of the package. And all usages depends on the resource will import and package and before anyone uses it, it is already initialized when the program loads the package. So you don't really have to do anything. However, this might not possible for class orientated language like Java.
Example: say you want to have a global database connection object shared by multiple subroutines. You just need to encapsulate it in a package and let the subroutines import it.
The Package Loading approach seem much simpler and clearer to implement. I don't see any benefits of doing Singleton class unless I am missing anything?
Aucun commentaire:
Enregistrer un commentaire