1 Creational Design Patterns
1 Creational Design Patterns
1
UML Revisited
Generalization
Dependency: “uses”
2
Creational Patterns to be Covered
ꟷFactory method
ꟷAbstract factory
ꟷBuilder
ꟷSingleton
3
Factory Method
4
Solution
5
Example: Drawing
<<interface>> Client
Shape
+ draw()
6
public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Similar implementation for Square and Circle
7
Example: Kiosk
<<interface>> Kiosk
PaymentProcessor
+ processPayment()
GetPayment
Cash CreditCard Coupon +getProcessor(type):
PaymentProcessor
+ prcessPayment() + prcessPayment() + prcessPayment()
8
Factory
9
10
11
Consequences
• Factory design pattern provides approach to code for interface rather
than implementation.
• Factory pattern removes the instantiation of actual implementation
classes from client code. Factory pattern makes our code more
robust, less coupled and easy to extend. For example, we can easily
change lower class implementation because client program is
unaware of this.
• Factory pattern provides abstraction between implementation and
client classes through inheritance.
12
Abstract Factory
13
Solution
14
Example: Car Factory
<<interface>> Client
HondaFactory
+ createEngine()
+ createTrans()
Engine
CivicFactory AccordFactory
+ createEngine() + createEngine()
+ createTrans() + createTrans()
CivicEngine AccordEngine
Transmission
CivicTrans AccordTrans
15
https://www.tutorialspoint.com/design_pattern/design_pattern
_quick_guide.htm
16
17
18
Abstract Factory
19
20
21
22
23
24
Consequences
• Isolates the concrete class
• Makes exchanging product family easy
• Promotes consistency among products
• Abstract Factory design pattern provides approach to code for
interface rather than implementation.
• Abstract Factory pattern is “factory of factories” and can be easily
extended to accommodate more products.
• Abstract Factory pattern is robust and avoid conditional logic of
Factory pattern.
• Supporting new types of products is difficult
25
Singleton
26
Solution
SingletonClass
- instance: SingletonClass
- SingletonClass()
+ getInstance(): SingletonClass
27
Example: DB Connection Manger
public class DbConnection{
private DbConnection() {
connection = connectToDatabase(dbUser,dbPassword,dbName);
}
return instance;
}
}
DbConnection connection=DbConnection.getDbConnection();
28
Consequences
• Controlled access to sole instance
• Reduced namespace
29
Builder
30
Solution
31
Examples
To create a computer,
different parts are assembled
depending upon the order
received by the customer
(e.g., a customer can demand
a 500 GB hard disk with an
Intel processor; another
customer can choose a 250
GB hard disk with an AMD
processor).
32
Consequences
• Lets you vary a product’s internal representation
33
34
35
36
Builder
37
38
39
40