Creation Pattern
Singleton Pattern
- Enforces one and only one object of a Singleton class.
- Has the Singleton object globally accessible.
public class ExampleSingleton {
//lazy construction
//the class varible is null if no instance is instantiated.
private static ExampleSingleton uniqueInstance = null;
private ExampleSingleton(){
...
}
//lazy construction of the instance
public static ExampleSingleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new ExampleSingleton();
}
return uniqueInstance;
}
}
Factory Method Pattern
The Factory Method design intent is to define an interface for creating objects, but let the subclasses decide which class to instantiate.
Benefits of Factory Objects
- Coding to an interface, not an implementation
- If there are multiple clients that want to instantiate the same set of classes, then by using a Factory object, you have cut out redundant code and made the software easier to modify.
Example
The interface will define the core logic, and its subclass will implemented those logic according to their needs. For the example below, each factory will need to create knife after they receive a order and then do sharpen/polish/package procedure, which follows a same business logic. But based on their own characteristic, the Factory will decide their own way to generate the knife that the budgetFactory will create budgetKnife, the luxuryFactory will create luxuryKnife.
public abstract class KnifeFactory {
public Knife orderKnife(String knifeType){
Knife knife = null;
//now creating a knife is a mthod in the class
knife = factory.createKnife(knifeType);
// prepare the Knife
knife.sharpen();
knife.polish();
knife.package();
return knife;
}
abstract Knife createKnife(String knifeType);
}
public BudgetKnifeFactory extends KnifeFactory {
//up to any subclass of KnifeStore to define this method
Knife createKnife(String knifeType){
if (knifeType.equals("steak")){
return new BudgetSteakKnife();
} else if (knifeType.equals("chefs")){
return new BudgetChefsKnife();
}
//.. more types
else return null;
}
}
public LuxuryKnifeFactory extends KnifeFactory {
//up to any subclass of KnifeStore to define this method
Knife createKnife(String knifeType){
if (knifeType.equals("steak")){
return new LuxurySteakKnife();
} else if (knifeType.equals("chefs")){
return new LuxuryChefsKnife();
}
//.. more types
else return null;
}
}