Software Design Patterns - Creational Patterns
Software Design Patterns - Creational Patterns
Deals with object creation mechanisms
- Singleton
- Builder
- Prototype
- Factory
- Abstract Factory
Singleton Pattern
A class of which only a single instance can exist
Application needs one, and only one, instance of an object.
Applicable when
- Ownership of the single instance cannot be reasonably assigned
- Lazy initialization is desirable
- Global access is not otherwise provided for
Basic version
1 | public final class singleton{ |
Lazy initialization version(Thread-Safe)
Pros: Initialised on first call to avoid memory wastage.
Cons: locks must be added to ensure thread safety, and adding locks will affect performance.
1 | public class Singleton { |
Initialiation-on-demand Holder Idiom
1 | public class Singleton { |
Builder Pattern
Complex objects can be created directly without the user knowing the construction process and details of the object.
Solves the Telescoping Problem.
Main parts of GoF’s Builder Pattern
Product object
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20public class Computer{
//电脑组件的集合
private List<String> parts = new ArrayList<String>();
//用于将组件组装到电脑里
public void Add(String part){
parts.add(part);
}
public void Show(){
for (int i = 0;i<parts.size();i++){
System.out.println(“组件”+parts.get(i)+“装好了”);
}
System.out.println(“电脑组装完成,请验收”);
}
}A Builder(interface or abstract class)
1 | public abstract class Builder { |
Concrete Builder(extend the Builder)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28//装机人员1
public class ConcreteBuilder extend Builder{
//创建产品实例
Computer computer = new Computer();
//组装产品
public void BuildCPU(){
computer.Add("组装CPU")
}
public void BuildMainboard(){
computer.Add("组装主板")
}
public void BuildHD(){
computer.Add("组装主板")
}
//返回组装成功的电脑
public Computer GetComputer(){
return computer
}
}Director object
1 | public class Director{ |
Prototype Pattern
Creating duplicate object while keeping performance in mind. The operation will directly clone a object in the ram. RAM’s I/O is much faster than storage.
- Creator
- Prototype
- ConcretePrototype
Factory Pattern
In the factory pattern, we create objects without exposing the creation logic to the public and by using a common interface to point to the newly created object.
There’re two type of Factory Pattern
- Simple Factory
- Simple Factory create products(object)
1
2
3
4
5
6
7
8
9
10public interface Dog{
public void speak();
};
public class Poodle implements Dog {
public void speak(){System.out.println("Poodle says \"arf\"")};
}
public class Rottweiler implements Dog {
public void speak(){System.out.println("Poodle says \"arf\"")};
}
- Simple Factory create products(object)
1 | public class DogFactory{ |
- Abstract Factory Pattern
- Abstract Factory create Factory
…write later…