Singleton Design Pattern Part 2
Created: 20 December 2012 Modified:In Part 1 of these articles we discussed the negative aspects of the Singleton Design Pattern. Now let us discuss what can be done to reduce the negative aspects. The first item that springs to mind is that we can loosen the coupling by returning an interface rather than the object itself. Keep in mind that by doing this it will no longer be a Singleton when considering a strict definition.
- Singleton Design Pattern Part 1
- Singleton Design Pattern Part 2]
- Singleton Source
RuleSystem.java
IRuleSystem.java
We now can change the object type being returned by the “Singleton” as long as it implements the IRuleSystem interface. We could create FantasyRule and SuperHeroRule classes that implement the IRuleSystem interface and return either one. We can add or remove a variety of rule systems to the RuleSystem class without changing code where the class is called. We can change the code in one location, which is the goal of being loosely coupled.
This design needs more thought. How will our RuleSystem class know which rule system to return? The option I am going with here is to pass in a parameter to the getInstance method. Let us write some code starting with our “Singleton” class.
RuleSystems.java
Wow! Our Singleton Design pattern has been transformed into a Factory Design pattern. Does this mean, when we are tempted to use a Singleton, we should instead use a Factory instead? I would say the answer is yes 99% of the time. Now for our Enumerations which will help keep our code uncluttered.
RuleSystemEnum.java
Next our simple interface.
IRuleSystem.java
Followed by two rule systems which implement our interface.
FantasyRuleSystem.java
SuperRuleSystem.java
Now lets add a class that will use our Factory and show us how it works.
SuperRuleSystem.java
When run you should see results similar to the following.
SingletonImproved Results
What hasn’t been addressed is the global nature of using Singleton’s and their affect on testing/debugging. I will leave those subjects to others for now as I am anxious to move onto another design pattern.
tags: