Singleton
Using this pattern, we can restrict the object creation task to a single class or object. If we have a scenario where we just use one object as the central co-coordinator object for communication, then this pattern is to be used.
Some of the steps (unordered) to be followed for this pattern are:
Important: A singleton need not always be static class. The static class is loaded in memory at application startup, while we can defer this loading in singletons by having them lazily constructed, requiring no memory or resources until needed.
Example:
The related source code is available in GitHub
References:
Using this pattern, we can restrict the object creation task to a single class or object. If we have a scenario where we just use one object as the central co-coordinator object for communication, then this pattern is to be used.
Some of the steps (unordered) to be followed for this pattern are:
- create a class that has a method to create new instance
- the new instance will only be created if one doesn't exist already, if one already exists, then the same object should be provided (returned)
- in multi-threaded application, access of the object creation part should be specially taken care and designed to be mutually exclusive (across all objects that access it)
Important: A singleton need not always be static class. The static class is loaded in memory at application startup, while we can defer this loading in singletons by having them lazily constructed, requiring no memory or resources until needed.
Example:
The related source code is available in GitHub
References:
No comments:
Post a Comment