I used my first pratical application of a bona-fide software design pattern today however: The Singleton. From what I gather, it's likely to simplest to understand and implement -- so... uh, it's nothing fancy.
The Singleton design pattern is used to ensure that only one instance, a "single instance" is ever instantiated during the life of an application. It can (and from what I understand, should) be used in place of a class composed entirely of static methods. The Singleton ensures that a single instance of the class is instantiated the first time a method in that class is requested, and then the same instance is accessed many times during the life of the application.
Implementaion of the Singleton requires applying three basic concepts:
- a protected constructor;
- a private static variable of the class type;
- and a public static method (typically named "instance") that controls the instantiation of new classes
Here's how it works:
- To instantiate a new class, the application calls the instance method rather than the typical "new class()" syntax.
- The intance method checks the private variable for null (meaning the class hasn't already been instantiated).
- If the protected variable is null, then the intance method calls the protected constructor which instatiates the class and returns the instance;
- if the protected variable is not null (ie: an instance already exists), then the instance method simply returns the already instantiated class.
Voila! Only one instance of a Singleton class can ever exists. It's really quite simple and elegant -- which I guess is what makes it really cool.
No comments:
Post a Comment