SlideShare a Scribd company logo
Design Pattern
part 1
Jieyi Wu
2017/10/25
GoF
Design Pattern
× Creational Patterns
× Structural Patterns
× Behavioral Patterns
1
Creational Pattern
2
× Singleton
× Simple Factory
× Factory
× Abstract Factory
× Builder
× Prototype
1.
Singleton
Pattern
• A class of which only a single instance can exist
3
UML diagram
4
Roles of the pattern
× Singleton
✦ Classic
✦ Thread-safe
✦ Synchronize the critical
✦ Thread-safe & Initialized
✦ Ultimate Thread-safe & efficient
5
Classic
Singleton
class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
6
Thread-safe
Singleton
class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
7
Synchronize
the critical
Singleton
class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
8
Thread-safe &
Initialized
Singleton
class Singleton {
private static Singleton instance = new
Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
9
Ultimate
Thread-safe &
efficient
Singleton
class Singleton {
private Singleton() {
}
private static class SingletonHolder {
private final static Singleton instance =
new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
10
Pros. & Cons.
✓ Providing an unique object.
✓ Saving the system resource and improving the system performance.
✗ No interface layer.
✗ Over-responsibility and anti SRP(Single Responsibility Principle).
✗ Abusing this pattern is easy to cause problems.
11
2.
Simple Factory
Pattern
12
12
UML diagram
13
Roles of the pattern
× Client
× Factory
× Product
× Concrete Product
14
Product &
Concrete
Product
abstract class Weapon {
public String name;
public Double attack;
public Double defense;
}
class Sword extends Weapon {}
class Blade extends Weapon {}
class Dagger extends Weapon {}
15
Simple
Factory
class WeaponFactory {
public Weapon create(String category) {
if ("sword".equals(category)) {
return new Sword();
}
else if ("blade".equals(category)) {
return new Blade();
}
else if ("dagger".equals(category)) {
return new Dagger();
}
return null;
}
}
16
Client
class Client {
public void main(String[] args) {
Weapon dagger = new
WeaponFactory().create("dagger");
Weapon sword = new
WeaponFactory().create("sword");
Weapon blade = new
WeaponFactory().create("blade");
User pokk = new User();
pokk.wield(dagger);
pokk.wield(blade);
}
}
17
Pros. & Cons.
✓ The business logic is inside of the factory.
✓ Don’t have to know the class name of a product.
✓ Adding a new product in factory without modifying on client.
✗ Gathering all creating process.
✗ It’s not easy to expend and maintain.
✗ Factory isn’t able to inherited.
18
3.
Factory
Pattern
• Creates an instance of several derived classes
19
UML diagram
20
Roles of the pattern
× Client
× Factory
× Concrete Factory
× Product
× Concrete Product
21
interface IWeaponFactory {
Weapon create(String level);
}
class SwordFactory implements IWeaponFactory {
public Weapon create(String level) {
if ("normal".equals(level)) {
return new Sword();
}
else if ("advanced".equals(level)) {
return new AdvancedSword();
}
return null;
}
}
class DaggerFactory implements IWeaponFactory
{
public Weapon create(String level) {
if ("normal".equals(level)) {
return new Dagger();
}
else if ("advanced".equals(level)) {
return new AdvancedDagger();
}
return null;
}
}
…
Factory &
Concrete
Factory
22
abstract class Weapon {
public String name;
public Double attack;
public Double defense;
}
class Sword extends Weapon {}
class AdvancedSword extends Weapon {}
class Blade extends Weapon {}
class AdvancedBlade extends Weapon {}
class Dagger extends Weapon {}
class AdvancedDagger extends Weapon {}
Product &
Concrete
Product
23
class Client {
public void main(String[] args) {
Weapon dagger = new
DaggerFactory().create("advanced");
Weapon sword = new
SwordFactory().create("normal");
Weapon blade = new
BladeFactory().create("advanced");
User pokk = new User();
pokk.wield(sword);
pokk.wield(blade);
}
}
Client
24
✓ Don’t have to care about the detail.
✓ Factories are also called polymorphism factory pattern.
✗ Concrete Factory class will increase.
Pros. & Cons.
25
4.
Abstract
Factory Pattern
• Creates an instance of several families of classes
26
UML diagram
27
Roles of the pattern
× Client
× Factory
× Concrete Factory
× Abstract Product
× Concrete Product
28
Product
abstract class Weapon {
public String name;
public Double attack;
public Double defense;
}
abstract class Equipment {
public String name;
public Double attack;
public Double defense;
}
abstract class Wrist extends Equipment {}
abstract class Armor extends Equipment {}
abstract class Boot extends Equipment {}
abstract class Helmet extends Equipment {}
29
class FireSword extends Weapon {}
class MagicStaff extends Weapon {}
class DragonWrist extends Wrist {}
class MagicGloves extends Wrist {}
class MerlinCloth extends Armor {}
class DragonArmor extends Armor {}
class MerlinShoes extends Boot {}
class DragonBoot extends Boot {}
class MerlinHat extends Helmet {}
class DragonHelmet extends Helmet {}
Concrete
Product
30
class WizardSetFactory implements ISetEquipment {
@Override
public Weapon createWeapon() {
return new MagicStaff();
}
@Override
public Wrist createWrist() {
return new MagicGloves();
}
@Override
public Armor createArmor() {
return new MerlinCloth();
}
@Override
public Boot createBoot() {
return new MerlinShoes();
}
@Override
public Helmet createHelmet() {
return new MerlinHat();
}
}
Concrete
Factory A
31
interface ISetEquipment {
Weapon createWeapon();
Wrist createWrist();
Armor createArmor();
Boot createBoot();
Helmet createHelmet();
}
Factory
32
class WarriorSetFactory implements ISetEquipment {
@Override
public Weapon createWeapon() {
return new FireSword();
}
@Override
public Wrist createWrist() {
return new DragonWrist();
}
@Override
public Armor createArmor() {
return new DragonArmor();
}
@Override
public Boot createBoot() {
return new DragonBoot();
}
@Override
public Helmet createHelmet() {
return new DragonHelmet();
}
}
Concrete
Factory B
33
class Client {
public void main(String[] args) {
WizardSetFactory wizardSetFactory = new
WizardSetFactory();
Weapon sword = wizardSetFactory.createWeapon();
Helmet helmet = wizardSetFactory.createHelmet();
Wrist wrist = wizardSetFactory.createWrist();
Armor armor = wizardSetFactory.createArmor();
Boot boot = wizardSetFactory.createBoot();
Warrior jieyi = new Warrior();
jieyi.wield(sword);
jieyi.wear(helmet, wrist, armor, boot);
WizardSetFactory wizardSetFactory = new
WizardSetFactory();
Weapon staff = wizardSetFactory.createWeapon();
Helmet hat = wizardSetFactory.createHelmet();
Wrist gloves = wizardSetFactory.createWrist();
Armor cloth = wizardSetFactory.createArmor();
Boot shoes = wizardSetFactory.createBoot();
Wizard pokk = new Wizard();
pokk.wield(staff);
pokk.wear(hat, gloves, cloth, shoes);
}
}
Client
34
Pros. & Cons.
✓ Separating the abstract factory and the product group.
✓ Guaranteeing the product group to work together.
✓ It’s easy to create a new concrete factory and following
OCP(Open Closed Principle).
✗ It’s not easy to add new category of products.
✗ Skewing OCP(Open Closed Principle).
35
5.
Builder
Pattern
• Separates object construction from its representation
36
UML diagram
37
Role of the pattern
× Director
× Builder
× Concrete Builder
× Product
38
Product
class Minion {
public String name;
public Double attack;
public Double defense;
public Weapon weapon;
public Equipment helmet;
public Equipment armor;
public Equipment boot;
public int money;
}
39
Builder
abstract class MinionBuilder {
protected Minion minion;
public abstract void buildName();
public abstract void buildWeapon();
public abstract void buildHelmet();
public abstract void buildArmor();
public abstract void buildBoot();
public Minion build() {
return minion;
}
}
40
Concrete
Builder A
class MinionA extends MinionBuilder {
@Override
public void buildName() {
minion.name = "MinionA";
}
@Override
public void buildWeapon() {
minion.weapon = new IceSword();
// To add some attributes from the weapon.
}
@Override
public void buildHelmet() {
minion.helmet = new Helmet();
// To add some attributes from the weapon.
}
@Override
public void buildArmor() {
minion.armor = new Armor();
// To add some attributes from the weapon.
}
@Override
public void buildBoot() {
minion.boot = new Boot();
// To add some attributes from the weapon.
}
}
41
Concrete
Builder B
class MinionB extends MinionBuilder {
@Override
public void buildName() {
minion.name = "Big Minion";
}
@Override
public void buildWeapon() {
minion.weapon = new Axe();
// To add some attributes from the weapon.
}
@Override
public void buildHelmet() {
minion.helmet = new KnightHelmet();
// To add some attributes from the weapon.
}
@Override
public void buildArmor() {
minion.helmet = new KnightArmor();
// To add some attributes from the weapon.
}
@Override
public void buildBoot() {
minion.boot = new KnightBoot();
// To add some attributes from the weapon.
}
}
42
Director
class Boss {
private MinionBuilder minionBuilder;
Boss(MinionBuilder minionBuilder) {
this.minionBuilder = minionBuilder;
}
public Minion summonMinion() {
minionBuilder.buildName();
minionBuilder.buildWeapon();
minionBuilder.buildHelmet();
minionBuilder.buildArmor();
minionBuilder.buildBoot();
return minionBuilder.build();
}
public void setBuilder(MinionBuilder minionBuilder) {
this.minionBuilder = minionBuilder;
}
}
43
Client
class Client {
public void main(String[] args) {
MinionA minionA = new MinionA();
MinionB minionB = new MinionB();
Boss worldBoss = new Boss(minionA);
for (int index = 0 ; 10 > index ; index++) {
worldBoss.summonMinion();
}
worldBoss.setBuilder(minionB);
for (int index = 0 ; 3 > index ; index++) {
worldBoss.summonMinion();
}
}
}
44
Alternative
Builder
There’s another common way to implement
the builder pattern.
45
Product &
Builder
class Minion {
public String name;
public Double attack;
public Double defense;
public Weapon weapon;
public Equipment helmet;
public Equipment armor;
public Equipment boot;
public int money;
public Minion(String name, Weapon weapon,
Equipment helmet, Equipment armor, Equipment
boot, int money) {
this.name = name;
this.weapon = weapon;
this.helmet = helmet;
this.armor = armor;
this.boot = boot;
this.money = money;
}
public static class MinionBuilder {
…
}
}
46
Builder
public static class MinionBuilder {
private String name;
private Weapon weapon;
private Equipment helmet;
private Equipment armor;
private Equipment boot;
private int money;
public MinionBuilder name(String name) {
this.name = name;
return this;
}
public MinionBuilder weapon(Weapon weapon) {
this.weapon = weapon;
return this;
}
public MinionBuilder helmet(Equipment helmet) {
this.helmet = helmet;
return this;
}
public MinionBuilder armor(Equipment armor) {
this.armor = armor;
return this;
}
public MinionBuilder boot(Equipment boot) {
this.boot = boot;
return this;
}
public MinionBuilder money(int money) {
this.money = money;
return this;
}
public Minion build() { return new Minion(name, weapon, helmet,
armor, boot, money); }
} 47
Director
class Boss {
public Minion summonMinion() {
return new Minion.MinionBuilder()
.name("Dragon Minion")
.weapon(new Claw())
.armor(new DragonArmor())
.helmet(new DragonHelmet())
.money(154000)
.build();
}
}
48
Client
class Client {
public void main(String[] args) {
Boss worldBoss = new Boss();
for (int index = 0 ; 10 > index ; index++) {
worldBoss.summonMinion();
}
}
}
49
Pros. & Cons.
✓ Decoupling the processing and the the products.
✓ Each of concrete builders is independent.
✓ Be able to control the processing detail.
✓ Expendable and following the OCP(Open Closed Principle).
✗ For the similar products.
✗ To fit the internal builder is complex, the builder might become
huge.
50
6.
Prototype
Pattern
• A fully initialized instance to be copied or cloned
51
UML diagram
52
Role of the pattern
× Client
× Prototype
× Concrete Prototype
53
Prototype
abstract class Weapon implements Cloneable {
public String name;
public Double attack;
public Double defense;
public Effect attackEffect;
}
54
Object
class Sword extends Weapon {
@Override
protected Object clone() {
Object clone = null;
try {
clone = super.clone();
((Weapon) clone).attackEffect = attackEffect.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
55
Client
class Client {
public void main(String[] args) {
Sword sword = new Sword();
Warrior pokk = new Warrior();
pokk.wield(sword);
Sword dupSword = (Sword) sword.clone();
}
}
56
Pros. & Cons.
✓ Creating a same object is easy.
✓ Keeping the same object state.
✓ Simplifying the construction.
✗ It’s complex when implementing deep clone.
✗ Implementing the clone interface to each of the classes.
57
Thanks!
Any questions?
58

More Related Content

What's hot (20)

PDF
The Ring programming language version 1.3 book - Part 7 of 88
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.9 book - Part 99 of 210
Mahmoud Samir Fayed
 
PPT
7 inheritance
Abhijit Gaikwad
 
PDF
Welcome to Modern C++
Seok-joon Yun
 
PDF
guice-servlet
Masaaki Yonebayashi
 
PDF
The Ring programming language version 1.6 book - Part 184 of 189
Mahmoud Samir Fayed
 
PPTX
classes & objects in cpp overview
gourav kottawar
 
PPTX
重構—改善既有程式的設計(chapter 9)
Chris Huang
 
DOCX
Java practical
shweta-sharma99
 
PPTX
重構—改善既有程式的設計(chapter 8)part 1
Chris Huang
 
PPTX
重構—改善既有程式的設計(chapter 8)part 2
Chris Huang
 
PDF
Contextual communications and why you should care - Droidcon DE
Marcos Placona
 
PDF
Concurrency Concepts in Java
Doug Hawkins
 
PDF
Mattbrenner
Droidcon Berlin
 
PDF
The Ring programming language version 1.5.1 book - Part 175 of 180
Mahmoud Samir Fayed
 
PPT
Java Threads
Kapish Joshi
 
PDF
The Ring programming language version 1.7 book - Part 91 of 196
Mahmoud Samir Fayed
 
PPT
Memory Management In C++
ShriKant Vashishtha
 
PDF
The Ring programming language version 1.5.3 book - Part 85 of 184
Mahmoud Samir Fayed
 
PPT
data Structure Lecture 1
Teksify
 
The Ring programming language version 1.3 book - Part 7 of 88
Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 99 of 210
Mahmoud Samir Fayed
 
7 inheritance
Abhijit Gaikwad
 
Welcome to Modern C++
Seok-joon Yun
 
guice-servlet
Masaaki Yonebayashi
 
The Ring programming language version 1.6 book - Part 184 of 189
Mahmoud Samir Fayed
 
classes & objects in cpp overview
gourav kottawar
 
重構—改善既有程式的設計(chapter 9)
Chris Huang
 
Java practical
shweta-sharma99
 
重構—改善既有程式的設計(chapter 8)part 1
Chris Huang
 
重構—改善既有程式的設計(chapter 8)part 2
Chris Huang
 
Contextual communications and why you should care - Droidcon DE
Marcos Placona
 
Concurrency Concepts in Java
Doug Hawkins
 
Mattbrenner
Droidcon Berlin
 
The Ring programming language version 1.5.1 book - Part 175 of 180
Mahmoud Samir Fayed
 
Java Threads
Kapish Joshi
 
The Ring programming language version 1.7 book - Part 91 of 196
Mahmoud Samir Fayed
 
Memory Management In C++
ShriKant Vashishtha
 
The Ring programming language version 1.5.3 book - Part 85 of 184
Mahmoud Samir Fayed
 
data Structure Lecture 1
Teksify
 

Viewers also liked (11)

PPTX
Let us understand design pattern
Mindfire Solutions
 
PPSX
Design Pattern Libraries
Brian Peppler
 
PPTX
Design Pattern - Factory Method Pattern
Mudasir Qazi
 
PPTX
Factory Method Pattern
Anjan Kumar Bollam
 
PDF
Design Patterns - The Ultimate Blueprint for Software
Edureka!
 
PPT
Design Patterns
Rafael Coutinho
 
PDF
Factory Design Pattern
Jyaasa Technologies
 
PPTX
Design Patterns - 01 Introduction and Decorator Pattern
eprafulla
 
KEY
Intro to Data Science for Enterprise Big Data
Paco Nathan
 
PPT
Design Patterns
soms_1
 
PDF
Big Data [sorry] & Data Science: What Does a Data Scientist Do?
Data Science London
 
Let us understand design pattern
Mindfire Solutions
 
Design Pattern Libraries
Brian Peppler
 
Design Pattern - Factory Method Pattern
Mudasir Qazi
 
Factory Method Pattern
Anjan Kumar Bollam
 
Design Patterns - The Ultimate Blueprint for Software
Edureka!
 
Design Patterns
Rafael Coutinho
 
Factory Design Pattern
Jyaasa Technologies
 
Design Patterns - 01 Introduction and Decorator Pattern
eprafulla
 
Intro to Data Science for Enterprise Big Data
Paco Nathan
 
Design Patterns
soms_1
 
Big Data [sorry] & Data Science: What Does a Data Scientist Do?
Data Science London
 
Ad

Similar to Design pattern - part 1 (20)

PPTX
Software Architecture and Design Patterns Notes.pptx
VivekanandaGN2
 
PPTX
OOPSDesign PPT ( introduction to opps and design (
bhfcvh531
 
PPTX
Gof design patterns
Srikanth R Vaka
 
PPT
Unit 2-Design Patterns.ppt
MsRAMYACSE
 
PPT
Design patterns
◄ vaquar khan ► ★✔
 
PPTX
design patter related ppt and presentation
Indu32
 
PPTX
Sda 8
AmberMughal5
 
PPSX
Prophecy Of Design Patterns
pradeepkothiyal
 
PPTX
Creational Design Patterns.pptx
Sachin Patidar
 
PPTX
Design pattern
Thibaut De Broca
 
PPT
P Training Presentation
Gaurav Tyagi
 
DOCX
Java Design Pattern Interview Questions
jbashask
 
PPT
Design pattern
Mallikarjuna G D
 
PPTX
PATTERNS02 - Creational Design Patterns
Michael Heron
 
PPTX
Design Patterns
Sergii Stets
 
PDF
27418524 design-patterns-dot-net-with-examples
Quang Suma
 
PPTX
Day5
madamewoolf
 
PPTX
Creational pattern 2
Naga Muruga
 
PDF
The maze of Design Patterns & SOLID Principles
Muhammad Raza
 
Software Architecture and Design Patterns Notes.pptx
VivekanandaGN2
 
OOPSDesign PPT ( introduction to opps and design (
bhfcvh531
 
Gof design patterns
Srikanth R Vaka
 
Unit 2-Design Patterns.ppt
MsRAMYACSE
 
design patter related ppt and presentation
Indu32
 
Prophecy Of Design Patterns
pradeepkothiyal
 
Creational Design Patterns.pptx
Sachin Patidar
 
Design pattern
Thibaut De Broca
 
P Training Presentation
Gaurav Tyagi
 
Java Design Pattern Interview Questions
jbashask
 
Design pattern
Mallikarjuna G D
 
PATTERNS02 - Creational Design Patterns
Michael Heron
 
Design Patterns
Sergii Stets
 
27418524 design-patterns-dot-net-with-examples
Quang Suma
 
Creational pattern 2
Naga Muruga
 
The maze of Design Patterns & SOLID Principles
Muhammad Raza
 
Ad

More from Jieyi Wu (8)

PPTX
Design pattern advanced ii with testing
Jieyi Wu
 
PDF
Design pattern advanced i
Jieyi Wu
 
PDF
Dependency injection
Jieyi Wu
 
PDF
Application architecture pattern
Jieyi Wu
 
PDF
Reactive X introduction part1
Jieyi Wu
 
PDF
Karitoke's supported technology
Jieyi Wu
 
PPTX
Nice to meet Kotlin
Jieyi Wu
 
PPTX
Object-oriented programming
Jieyi Wu
 
Design pattern advanced ii with testing
Jieyi Wu
 
Design pattern advanced i
Jieyi Wu
 
Dependency injection
Jieyi Wu
 
Application architecture pattern
Jieyi Wu
 
Reactive X introduction part1
Jieyi Wu
 
Karitoke's supported technology
Jieyi Wu
 
Nice to meet Kotlin
Jieyi Wu
 
Object-oriented programming
Jieyi Wu
 

Recently uploaded (20)

PPTX
quantum computing transition from classical mechanics.pptx
gvlbcy
 
PPTX
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
PPTX
Water resources Engineering GIS KRT.pptx
Krunal Thanki
 
PPTX
Basics of Auto Computer Aided Drafting .pptx
Krunal Thanki
 
PDF
Air -Powered Car PPT by ER. SHRESTH SUDHIR KOKNE.pdf
SHRESTHKOKNE
 
PDF
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PPTX
ENSA_Module_7.pptx_wide_area_network_concepts
RanaMukherjee24
 
PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PDF
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
PDF
CAD-CAM U-1 Combined Notes_57761226_2025_04_22_14_40.pdf
shailendrapratap2002
 
PPTX
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
PDF
Machine Learning All topics Covers In This Single Slides
AmritTiwari19
 
PPTX
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
PDF
STUDY OF NOVEL CHANNEL MATERIALS USING III-V COMPOUNDS WITH VARIOUS GATE DIEL...
ijoejnl
 
PDF
All chapters of Strength of materials.ppt
girmabiniyam1234
 
PDF
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
PPTX
sunil mishra pptmmmmmmmmmmmmmmmmmmmmmmmmm
singhamit111
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
quantum computing transition from classical mechanics.pptx
gvlbcy
 
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
Water resources Engineering GIS KRT.pptx
Krunal Thanki
 
Basics of Auto Computer Aided Drafting .pptx
Krunal Thanki
 
Air -Powered Car PPT by ER. SHRESTH SUDHIR KOKNE.pdf
SHRESTHKOKNE
 
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
ENSA_Module_7.pptx_wide_area_network_concepts
RanaMukherjee24
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
CAD-CAM U-1 Combined Notes_57761226_2025_04_22_14_40.pdf
shailendrapratap2002
 
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
Machine Learning All topics Covers In This Single Slides
AmritTiwari19
 
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
STUDY OF NOVEL CHANNEL MATERIALS USING III-V COMPOUNDS WITH VARIOUS GATE DIEL...
ijoejnl
 
All chapters of Strength of materials.ppt
girmabiniyam1234
 
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
sunil mishra pptmmmmmmmmmmmmmmmmmmmmmmmmm
singhamit111
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 

Design pattern - part 1

  • 2. GoF Design Pattern × Creational Patterns × Structural Patterns × Behavioral Patterns 1
  • 3. Creational Pattern 2 × Singleton × Simple Factory × Factory × Abstract Factory × Builder × Prototype
  • 4. 1. Singleton Pattern • A class of which only a single instance can exist 3
  • 6. Roles of the pattern × Singleton ✦ Classic ✦ Thread-safe ✦ Synchronize the critical ✦ Thread-safe & Initialized ✦ Ultimate Thread-safe & efficient 5
  • 7. Classic Singleton class Singleton { private static Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } 6
  • 8. Thread-safe Singleton class Singleton { private static Singleton instance = null; private Singleton() { } public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } 7
  • 9. Synchronize the critical Singleton class Singleton { private static Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } 8
  • 10. Thread-safe & Initialized Singleton class Singleton { private static Singleton instance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return instance; } } 9
  • 11. Ultimate Thread-safe & efficient Singleton class Singleton { private Singleton() { } private static class SingletonHolder { private final static Singleton instance = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.instance; } } 10
  • 12. Pros. & Cons. ✓ Providing an unique object. ✓ Saving the system resource and improving the system performance. ✗ No interface layer. ✗ Over-responsibility and anti SRP(Single Responsibility Principle). ✗ Abusing this pattern is easy to cause problems. 11
  • 15. Roles of the pattern × Client × Factory × Product × Concrete Product 14
  • 16. Product & Concrete Product abstract class Weapon { public String name; public Double attack; public Double defense; } class Sword extends Weapon {} class Blade extends Weapon {} class Dagger extends Weapon {} 15
  • 17. Simple Factory class WeaponFactory { public Weapon create(String category) { if ("sword".equals(category)) { return new Sword(); } else if ("blade".equals(category)) { return new Blade(); } else if ("dagger".equals(category)) { return new Dagger(); } return null; } } 16
  • 18. Client class Client { public void main(String[] args) { Weapon dagger = new WeaponFactory().create("dagger"); Weapon sword = new WeaponFactory().create("sword"); Weapon blade = new WeaponFactory().create("blade"); User pokk = new User(); pokk.wield(dagger); pokk.wield(blade); } } 17
  • 19. Pros. & Cons. ✓ The business logic is inside of the factory. ✓ Don’t have to know the class name of a product. ✓ Adding a new product in factory without modifying on client. ✗ Gathering all creating process. ✗ It’s not easy to expend and maintain. ✗ Factory isn’t able to inherited. 18
  • 20. 3. Factory Pattern • Creates an instance of several derived classes 19
  • 22. Roles of the pattern × Client × Factory × Concrete Factory × Product × Concrete Product 21
  • 23. interface IWeaponFactory { Weapon create(String level); } class SwordFactory implements IWeaponFactory { public Weapon create(String level) { if ("normal".equals(level)) { return new Sword(); } else if ("advanced".equals(level)) { return new AdvancedSword(); } return null; } } class DaggerFactory implements IWeaponFactory { public Weapon create(String level) { if ("normal".equals(level)) { return new Dagger(); } else if ("advanced".equals(level)) { return new AdvancedDagger(); } return null; } } … Factory & Concrete Factory 22
  • 24. abstract class Weapon { public String name; public Double attack; public Double defense; } class Sword extends Weapon {} class AdvancedSword extends Weapon {} class Blade extends Weapon {} class AdvancedBlade extends Weapon {} class Dagger extends Weapon {} class AdvancedDagger extends Weapon {} Product & Concrete Product 23
  • 25. class Client { public void main(String[] args) { Weapon dagger = new DaggerFactory().create("advanced"); Weapon sword = new SwordFactory().create("normal"); Weapon blade = new BladeFactory().create("advanced"); User pokk = new User(); pokk.wield(sword); pokk.wield(blade); } } Client 24
  • 26. ✓ Don’t have to care about the detail. ✓ Factories are also called polymorphism factory pattern. ✗ Concrete Factory class will increase. Pros. & Cons. 25
  • 27. 4. Abstract Factory Pattern • Creates an instance of several families of classes 26
  • 29. Roles of the pattern × Client × Factory × Concrete Factory × Abstract Product × Concrete Product 28
  • 30. Product abstract class Weapon { public String name; public Double attack; public Double defense; } abstract class Equipment { public String name; public Double attack; public Double defense; } abstract class Wrist extends Equipment {} abstract class Armor extends Equipment {} abstract class Boot extends Equipment {} abstract class Helmet extends Equipment {} 29
  • 31. class FireSword extends Weapon {} class MagicStaff extends Weapon {} class DragonWrist extends Wrist {} class MagicGloves extends Wrist {} class MerlinCloth extends Armor {} class DragonArmor extends Armor {} class MerlinShoes extends Boot {} class DragonBoot extends Boot {} class MerlinHat extends Helmet {} class DragonHelmet extends Helmet {} Concrete Product 30
  • 32. class WizardSetFactory implements ISetEquipment { @Override public Weapon createWeapon() { return new MagicStaff(); } @Override public Wrist createWrist() { return new MagicGloves(); } @Override public Armor createArmor() { return new MerlinCloth(); } @Override public Boot createBoot() { return new MerlinShoes(); } @Override public Helmet createHelmet() { return new MerlinHat(); } } Concrete Factory A 31
  • 33. interface ISetEquipment { Weapon createWeapon(); Wrist createWrist(); Armor createArmor(); Boot createBoot(); Helmet createHelmet(); } Factory 32
  • 34. class WarriorSetFactory implements ISetEquipment { @Override public Weapon createWeapon() { return new FireSword(); } @Override public Wrist createWrist() { return new DragonWrist(); } @Override public Armor createArmor() { return new DragonArmor(); } @Override public Boot createBoot() { return new DragonBoot(); } @Override public Helmet createHelmet() { return new DragonHelmet(); } } Concrete Factory B 33
  • 35. class Client { public void main(String[] args) { WizardSetFactory wizardSetFactory = new WizardSetFactory(); Weapon sword = wizardSetFactory.createWeapon(); Helmet helmet = wizardSetFactory.createHelmet(); Wrist wrist = wizardSetFactory.createWrist(); Armor armor = wizardSetFactory.createArmor(); Boot boot = wizardSetFactory.createBoot(); Warrior jieyi = new Warrior(); jieyi.wield(sword); jieyi.wear(helmet, wrist, armor, boot); WizardSetFactory wizardSetFactory = new WizardSetFactory(); Weapon staff = wizardSetFactory.createWeapon(); Helmet hat = wizardSetFactory.createHelmet(); Wrist gloves = wizardSetFactory.createWrist(); Armor cloth = wizardSetFactory.createArmor(); Boot shoes = wizardSetFactory.createBoot(); Wizard pokk = new Wizard(); pokk.wield(staff); pokk.wear(hat, gloves, cloth, shoes); } } Client 34
  • 36. Pros. & Cons. ✓ Separating the abstract factory and the product group. ✓ Guaranteeing the product group to work together. ✓ It’s easy to create a new concrete factory and following OCP(Open Closed Principle). ✗ It’s not easy to add new category of products. ✗ Skewing OCP(Open Closed Principle). 35
  • 37. 5. Builder Pattern • Separates object construction from its representation 36
  • 39. Role of the pattern × Director × Builder × Concrete Builder × Product 38
  • 40. Product class Minion { public String name; public Double attack; public Double defense; public Weapon weapon; public Equipment helmet; public Equipment armor; public Equipment boot; public int money; } 39
  • 41. Builder abstract class MinionBuilder { protected Minion minion; public abstract void buildName(); public abstract void buildWeapon(); public abstract void buildHelmet(); public abstract void buildArmor(); public abstract void buildBoot(); public Minion build() { return minion; } } 40
  • 42. Concrete Builder A class MinionA extends MinionBuilder { @Override public void buildName() { minion.name = "MinionA"; } @Override public void buildWeapon() { minion.weapon = new IceSword(); // To add some attributes from the weapon. } @Override public void buildHelmet() { minion.helmet = new Helmet(); // To add some attributes from the weapon. } @Override public void buildArmor() { minion.armor = new Armor(); // To add some attributes from the weapon. } @Override public void buildBoot() { minion.boot = new Boot(); // To add some attributes from the weapon. } } 41
  • 43. Concrete Builder B class MinionB extends MinionBuilder { @Override public void buildName() { minion.name = "Big Minion"; } @Override public void buildWeapon() { minion.weapon = new Axe(); // To add some attributes from the weapon. } @Override public void buildHelmet() { minion.helmet = new KnightHelmet(); // To add some attributes from the weapon. } @Override public void buildArmor() { minion.helmet = new KnightArmor(); // To add some attributes from the weapon. } @Override public void buildBoot() { minion.boot = new KnightBoot(); // To add some attributes from the weapon. } } 42
  • 44. Director class Boss { private MinionBuilder minionBuilder; Boss(MinionBuilder minionBuilder) { this.minionBuilder = minionBuilder; } public Minion summonMinion() { minionBuilder.buildName(); minionBuilder.buildWeapon(); minionBuilder.buildHelmet(); minionBuilder.buildArmor(); minionBuilder.buildBoot(); return minionBuilder.build(); } public void setBuilder(MinionBuilder minionBuilder) { this.minionBuilder = minionBuilder; } } 43
  • 45. Client class Client { public void main(String[] args) { MinionA minionA = new MinionA(); MinionB minionB = new MinionB(); Boss worldBoss = new Boss(minionA); for (int index = 0 ; 10 > index ; index++) { worldBoss.summonMinion(); } worldBoss.setBuilder(minionB); for (int index = 0 ; 3 > index ; index++) { worldBoss.summonMinion(); } } } 44
  • 46. Alternative Builder There’s another common way to implement the builder pattern. 45
  • 47. Product & Builder class Minion { public String name; public Double attack; public Double defense; public Weapon weapon; public Equipment helmet; public Equipment armor; public Equipment boot; public int money; public Minion(String name, Weapon weapon, Equipment helmet, Equipment armor, Equipment boot, int money) { this.name = name; this.weapon = weapon; this.helmet = helmet; this.armor = armor; this.boot = boot; this.money = money; } public static class MinionBuilder { … } } 46
  • 48. Builder public static class MinionBuilder { private String name; private Weapon weapon; private Equipment helmet; private Equipment armor; private Equipment boot; private int money; public MinionBuilder name(String name) { this.name = name; return this; } public MinionBuilder weapon(Weapon weapon) { this.weapon = weapon; return this; } public MinionBuilder helmet(Equipment helmet) { this.helmet = helmet; return this; } public MinionBuilder armor(Equipment armor) { this.armor = armor; return this; } public MinionBuilder boot(Equipment boot) { this.boot = boot; return this; } public MinionBuilder money(int money) { this.money = money; return this; } public Minion build() { return new Minion(name, weapon, helmet, armor, boot, money); } } 47
  • 49. Director class Boss { public Minion summonMinion() { return new Minion.MinionBuilder() .name("Dragon Minion") .weapon(new Claw()) .armor(new DragonArmor()) .helmet(new DragonHelmet()) .money(154000) .build(); } } 48
  • 50. Client class Client { public void main(String[] args) { Boss worldBoss = new Boss(); for (int index = 0 ; 10 > index ; index++) { worldBoss.summonMinion(); } } } 49
  • 51. Pros. & Cons. ✓ Decoupling the processing and the the products. ✓ Each of concrete builders is independent. ✓ Be able to control the processing detail. ✓ Expendable and following the OCP(Open Closed Principle). ✗ For the similar products. ✗ To fit the internal builder is complex, the builder might become huge. 50
  • 52. 6. Prototype Pattern • A fully initialized instance to be copied or cloned 51
  • 54. Role of the pattern × Client × Prototype × Concrete Prototype 53
  • 55. Prototype abstract class Weapon implements Cloneable { public String name; public Double attack; public Double defense; public Effect attackEffect; } 54
  • 56. Object class Sword extends Weapon { @Override protected Object clone() { Object clone = null; try { clone = super.clone(); ((Weapon) clone).attackEffect = attackEffect.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; } } 55
  • 57. Client class Client { public void main(String[] args) { Sword sword = new Sword(); Warrior pokk = new Warrior(); pokk.wield(sword); Sword dupSword = (Sword) sword.clone(); } } 56
  • 58. Pros. & Cons. ✓ Creating a same object is easy. ✓ Keeping the same object state. ✓ Simplifying the construction. ✗ It’s complex when implementing deep clone. ✗ Implementing the clone interface to each of the classes. 57