SlideShare a Scribd company logo
Design Pattern
part 2
Jieyi Wu
2017/11/27
GoF
Design Pattern
× Creational Patterns
× Structural
Patterns
× Behavioral
Patterns 1
Structural Pattern
2
× Adapter
× Bridge
× Composite
× Decorator
× Facade
× Flyweight
× Proxy
1.
Adapter
Pattern
• Match interfaces of different classes
3
UML diagram
4
Roles of the
pattern
× Target
× Adaptee
× Adapter
5
Target
6
interface IMinion {
void DoAttack();
void DoDefense();
}
class Captain implements IMinion {
@Override
public void DoAttack() {
// Do Captain attack.
}
@Override
public void DoDefense() {
// Do Captain defense.
}
}
class Rookie implements IMinion {
@Override
public void DoAttack() {
// Do Rookie attack.
}
@Override
public void DoDefense() {
// Do Rookie defense.
}
}
Adaptee
7
interface IEnemy {
void DoFire();
void DoGuard();
}
class Boss implements IEnemy {
@Override
public void DoFire() {
// Do something.
}
@Override
public void DoGuard() {
// Do something.
}
}
Adaptor
8
class AdapterMinion implements IMinion {
private final IEnemy iEnemy;
AdapterMinion(IEnemy iEnemy) {
this.iEnemy = iEnemy;
}
@Override
public void DoAttack() {
iEnemy.DoFire();
}
@Override
public void DoDefense() {
iEnemy.DoGuard();
}
}
Client
9
public class Client {
static public void main(String[] args) {
IMinion rookie = new Rookie();
rookie.DoAttack();
IMinion enemy = new AdapterMinion(new Boss());
enemy.DoAttack();
enemy.DoDefense();
}
}
10
Pros. & Cons.
✓ Though the adapter, the original code isn’t modified.
✓ Expandable and adaptable, following OCP(Open Close Principle).
✓ For client, clear; For adapter, reusable.
✗ It unnecessarily increases the size of the code as class
inheritance is less used and lot of code is needlessly duplicated
between classes.
11
2.
Bridge
Pattern
12
12
• Separates an object’s interface from its implementation
UML diagram
13
Roles of the
pattern
× Abstraction
× Refined Abstraction
× Implementor
× Concrete Implementor
14
Abstraction
15
abstract class IMinion {
protected final IWeapon weapon;
protected IMinion(IWeapon weapon) {
this.weapon = weapon;
}
abstract void DoAttack();
}
Refined
Abstraction
16
class Solider extends IMinion {
protected Solider(IWeapon weapon) {
super(weapon);
}
@Override
void DoAttack() {
weapon.Fire();
}
}
class Enemy extends IMinion {
protected Enemy(IWeapon weapon) {
super(weapon);
}
@Override
void DoAttack() {
weapon.Fire();
}
}
Implementor
17
interface IWeapon {
void Fire();
}
Concrete
Implementor
18
class Gun implements IWeapon {
@Override
public void Fire() {
// Shoot operation.
}
}
class Rocket implements IWeapon {
@Override
public void Fire() {
// Fire operation.
}
}
Client
19
public class Client {
static public void main(String[] args) {
IMinion solider = new Solider(new
Rocket());
solider.DoAttack();
IMinion enemy = new Enemy(new Gun());
enemy.DoAttack();
}
}
20
Pros. & Cons.
✓ Decouple the interface & the implement.
✓ Improving the expandability of the system, but anti SRP.
✓ This pattern is diaphanous for Client and hide the detail.
✗ The system becomes complexity and incomprehensible.
21
3.
Composite
Pattern
• A tree structure of simple and composite objects
22
UML diagram
23
Roles of the
pattern
× Component
× Leaf
× Composite
24
Component
25
abstract class MenuComponent {
public void add(MenuComponent menuComponent) {
throw new UnsupportedOperationException();
}
public void remove(MenuComponent menuComponent) {
throw new UnsupportedOperationException();
}
public MenuComponent getChild(int i) {
throw new UnsupportedOperationException();
}
public String getName() {
throw new UnsupportedOperationException();
}
public String getDescription() {
throw new UnsupportedOperationException();
}
public double getAttackValue() {
throw new UnsupportedOperationException();
}
public double getDefenseValue() {
throw new UnsupportedOperationException();
}
}
Composite
26
class Menu extends MenuComponent {
private final String name;
private final String description;
private ArrayList components = new ArrayList<MenuComponent>();
Menu(String name, String description) {
this.name = name;
this.description = description;
}
@Override
public void add(MenuComponent menuComponent) {
components.add(menuComponent);
}
@Override
public void remove(MenuComponent menuComponent) {
components.remove(menuComponent);
}
@Override
public MenuComponent getChild(int i) {
return (MenuComponent) components.get(i);
}
@Override
public String getName() {return name;}
@Override
public String getDescription() {return description;}
}
Leaf
27
class MenuItem extends MenuComponent {
private String name;
private String description;
private final double attack;
private final double defense;
MenuItem(String name, String description, double attack,
double defense) {
this.name = name;
this.description = description;
this.attack = attack;
this.defense = defense;
}
@Override
public String getName() {return name;}
@Override
public String getDescription() {return description;}
@Override
public double getAttackValue() {return attack;}
@Override
public double getDefenseValue() {return defense;}
}
Client
28
public class Client {
static public void main(String[] args) {
MenuComponent weaponMenu = new Menu("Weapon", "Hero's weapon menu");
MenuComponent clothMenu = new Menu("Cloth", "Hero's cloth menu");
MenuComponent trouserMenu = new Menu("Trouser", "Hero's armor menu");
MenuComponent all = new Menu("Root menu", "Top");
all.add(weaponMenu);
all.add(clothMenu);
all.add(trouserMenu);
weaponMenu.add(new MenuItem("Sword", "Sword", 10, 0));
weaponMenu.add(new MenuItem("Blade", "Blade", 6, 0));
weaponMenu.add(new MenuItem("Axe", "Axe", 14, 3));
clothMenu.add(new MenuItem("Cloth", "Cloth", 0, 6));
clothMenu.add(new MenuItem("Magic Cloth", "Magic Cloth", 0, 3));
clothMenu.add(new MenuItem("Knight Armor", "Knight Armor", 0, 10));
trouserMenu.add(new MenuItem("Trouser", "Trouser", 0, 10));
trouserMenu.add(new MenuItem("Knight Pants", "Knight Pants", 0, 4));
trouserMenu.add(new MenuItem("Underwear", "Underwear", 0, 8));
}
}
29
✓ Separating the layer objects and adding a new object easily.
✓ Client can operate leaves & composite object consistently.
✓ Adding a new composite object easily.
✗ Design will be more abstract.
Pros. & Cons.
30
4.
Decorator
Pattern
• Add responsibilities to objects dynamically
31
UML diagram
32
Roles of the
pattern
× Component
× Concrete Component
× Decorator
× Concrete Decorator
33
Component
34
interface IWeapon {
float attack = 0;
float defense = 0;
float currentAttack();
float currentDefense();
}
Concrete
Component
35
class Sword implements IWeapon {
float attack = 10;
float defense = 0;
@Override
public float currentAttack() {
return attack;
}
@Override
public float currentDefense() {
return defense;
}
}
class Axe implements IWeapon {
float attack = 15;
float defense = 5;
@Override
public float currentAttack() {
return attack;
}
@Override
public float currentDefense() {
return defense;
}
}
Decorator
36
abstract class Decorator implements IWeapon {
private final IWeapon weapon;
Decorator(IWeapon weapon) {
this.weapon = weapon;
}
@Override
public float currentAttack() {
return weapon.currentAttack();
}
@Override
public float currentDefense() {
return weapon.currentDefense();
}
}
Concrete
Decorator
37
class ThunderDecorator extends Decorator {
ThunderDecorator(IWeapon weapon) {
super(weapon);
}
@Override
public float currentAttack() {
return super.currentAttack() + 15;
}
@Override
public float currentDefense() {
return super.currentDefense() + 5;
}
}
class FireDecorator extends Decorator {
FireDecorator(IWeapon weapon) {
super(weapon);
}
@Override
public float currentAttack() {
return super.currentAttack() + 10;
}
@Override
public float currentDefense() {
return super.currentDefense();
}
}
Concrete
Decorator
38
class PoisonDecorator extends Decorator {
PoisonDecorator(IWeapon weapon) {
super(weapon);
}
@Override
public float currentAttack() {
return super.currentAttack() + 20;
}
@Override
public float currentDefense() {
return super.currentDefense();
}
}
Client
39
public class Client {
static public void main(String[] args) {
IWeapon powerSword =
new FireDecorator(
new PoisonDecorator(new Sword()));
IWeapon magicAxe =
new ThunderDecorator(
new FireDecorator(new Axe()));
}
}
Pros. & Cons.
40
✓ Decorator is more flexible than inheritance.
✓ Decorator can expand the functions of an object.
✓ Decorators of them combined can create various objects.
✓ Following the OCP(Open Closed Principle).
✗ Because when using the decorator pattern, there’re many
objects are created.
✗ It becomes more difficult to debug.
5.
Facade
Pattern
• A single class that represents an entire subsystem
41
UML diagram
42
Role of the pattern
× Façade
× SubSystems
43
Subsystem
44
class WarriorRoles {}
class MagicianRoles {}
class HunterRoles {}
class KnightRoles {}
class Minions {}
Facade
45
class Stage {
private final WarriorRoles warriorRoles;
private final MagicianRoles magicianRoles;
private final HunterRoles hunterRoles;
private final KnightRoles knightRoles;
private final Minions minions;
Stage(WarriorRoles warriorRoles, MagicianRoles magicianRoles,
HunterRoles hunterRoles, KnightRoles knightRoles,
Minions minions) {
this.warriorRoles = warriorRoles;
this.magicianRoles = magicianRoles;
this.hunterRoles = hunterRoles;
this.knightRoles = knightRoles;
this.minions = minions;
}
public void StageIce() {
warriorRoles.off();
magicianRoles.off();
hunterRoles.on();
knightRoles.off();
minions.quantity(200);
}
public void StageAirCastle() {
warriorRoles.on();
magicianRoles.off();
hunterRoles.off();
knightRoles.on();
minions.quantity(1000);
}
}
Client
46
public class Client {
static public void main(String[] args) {
Stage stage = new Stage(new WarriorRoles(),
new MagicianRoles(),
new HunterRoles(),
new KnightRoles(),
new Minions());
stage.StageIce();
stage.StageAirCastle();
}
}
Pros. & Cons.
✓ Reducing the dependency between the subsystem.
✓ Doesn’t have to care about the subsystem.
✓ Providing only one entry for using the object.
✗ If Client cant constrain to use subsystem well, it will
decrease the flexibility and variability.
✗ Anti OCP(Open Closed Principle).
47
6.
Flyweight
Pattern
• A fine-grained instance used for efficient sharing
48
UML diagram
49
Role of the pattern
× Flyweight
× Concrete Flyweight
× Flyweight Factory
× Client
50
Flyweight
51
abstract class Flyweight {
abstract void plant(int x, int y);
}
Concrete
Flyweight
52
class Tree extends Flyweight {
private int pX = 0, pY = 0;
private int height = 100;
private double leafQuantity = 0.7f;
private int leafColor = 0x1100ff;
@Override
void plant(int x, int y) {
pX = x;
pY = y;
// Do something.
}
}
class Grass extends Flyweight {
private int pX = 0, pY = 0;
private double leafQuantity = 0.2f;
private int leafColor = 0x0000ff;
@Override
void plant(int x, int y) {
pX = x;
pY = y;
// Do something.
}
}
Flyweight
Factory
53
class FlyweightFactory {
private final HashMap<String, Flyweight> pool =
new HashMap<>();
public Flyweight getFlyweight(String key) {
if (null == pool.get(key)) {
Flyweight object;
if (Objects.equals("grass", key)) {
object = new Grass();
}
else if (Objects.equals("tree", key)) {
object = new Tree();
}
pool.put(key, object);
}
return pool.get(key);
}
public int getFlyweightCount() {
return pool.size();
}
}
Client
54
public class Client {
static public void main(String[] args) {
FlyweightFactory flyweightFactory = new
FlyweightFactory();
flyweightFactory.getFlyweight("tree").plant
(3, 6);
flyweightFactory.getFlyweight("grass").plant
(1, 3);
flyweightFactory.getFlyweight("grass").plant
(2, 6);
flyweightFactory.getFlyweight("tree").plant
(1, 0);
}
}
Pros. & Cons.
✓ Reducing the objects quantity in the memory.
✓ The flyweight’s state is dependent.
✗ The system will be more complexity because separating the
internal & external state.
55
7.
Proxy
Pattern
• An object representing another object
56
UML diagram
57
Role of the pattern
× Subject
× Proxy
× RealSubject
58
Subject
59
interface IAttack {
void doAttack();
}
Proxy
60
class Proxy implements IAttack {
private final IAttack subject;
public Proxy(IAttack subject) {
this.subject = subject;
}
@Override
public void doAttack() {
// Do professional attack!!!
}
}
RealSubject
61
class Player implements IAttack {
@Override
public void doAttack() {
// Do attack.
}
}
Client
62
public class Client {
static public void main(String[] args) {
IAttack proxy = new Proxy(new Player());
proxy.doAttack();
}
}
Pros. & Cons.
✓ Hide the real subject to avoid the Client uses it directly.
✗ The operation speed will be lower.
✗ For implementing the proxy, there’re many extra works and some
proxy’s implementation is really complexity.
63
Thanks!
Any questions?
64
Ad

More Related Content

What's hot (20)

Advance features of C++
Advance features of C++Advance features of C++
Advance features of C++
vidyamittal
 
openFrameworks 007 - video
openFrameworks 007 - videoopenFrameworks 007 - video
openFrameworks 007 - video
roxlu
 
The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189
Mahmoud Samir Fayed
 
Mattbrenner
MattbrennerMattbrenner
Mattbrenner
Droidcon Berlin
 
openFrameworks 007 - graphics
openFrameworks 007 - graphicsopenFrameworks 007 - graphics
openFrameworks 007 - graphics
roxlu
 
Java practical
Java practicalJava practical
Java practical
shweta-sharma99
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196
Mahmoud Samir Fayed
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3D
roxlu
 
Java Threads
Java ThreadsJava Threads
Java Threads
Kapish Joshi
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
Doug Hawkins
 
重構—改善既有程式的設計(chapter 9)
重構—改善既有程式的設計(chapter 9)重構—改善既有程式的設計(chapter 9)
重構—改善既有程式的設計(chapter 9)
Chris Huang
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
chetan_p211
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
gourav kottawar
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Sergey Platonov
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
Nitay Neeman
 
openFrameworks 007 - GL
openFrameworks 007 - GL openFrameworks 007 - GL
openFrameworks 007 - GL
roxlu
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
Devnology
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
sidra tauseef
 
Csphtp1 09
Csphtp1 09Csphtp1 09
Csphtp1 09
HUST
 
Advance features of C++
Advance features of C++Advance features of C++
Advance features of C++
vidyamittal
 
openFrameworks 007 - video
openFrameworks 007 - videoopenFrameworks 007 - video
openFrameworks 007 - video
roxlu
 
The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189
Mahmoud Samir Fayed
 
openFrameworks 007 - graphics
openFrameworks 007 - graphicsopenFrameworks 007 - graphics
openFrameworks 007 - graphics
roxlu
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196
Mahmoud Samir Fayed
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3D
roxlu
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
Doug Hawkins
 
重構—改善既有程式的設計(chapter 9)
重構—改善既有程式的設計(chapter 9)重構—改善既有程式的設計(chapter 9)
重構—改善既有程式的設計(chapter 9)
Chris Huang
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
gourav kottawar
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Sergey Platonov
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
Nitay Neeman
 
openFrameworks 007 - GL
openFrameworks 007 - GL openFrameworks 007 - GL
openFrameworks 007 - GL
roxlu
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
Devnology
 
Csphtp1 09
Csphtp1 09Csphtp1 09
Csphtp1 09
HUST
 

Similar to Design pattern part 2 - structural pattern (20)

Day5
Day5Day5
Day5
madamewoolf
 
Prophecy Of Design Patterns
Prophecy Of Design PatternsProphecy Of Design Patterns
Prophecy Of Design Patterns
pradeepkothiyal
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Betclic Everest Group Tech Team
 
M04_DesignPatterns software engineering.ppt
M04_DesignPatterns software engineering.pptM04_DesignPatterns software engineering.ppt
M04_DesignPatterns software engineering.ppt
ssuser2d043c
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
Srikanth R Vaka
 
Introduction to Design Patterns
Introduction to Design PatternsIntroduction to Design Patterns
Introduction to Design Patterns
Prageeth Sandakalum
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
Mohammad Shaker
 
EXACT IMPLEMENTATION OF DESIGN PATTERNS IN C# LANGUAGE
EXACT IMPLEMENTATION OF DESIGN PATTERNS IN C# LANGUAGEEXACT IMPLEMENTATION OF DESIGN PATTERNS IN C# LANGUAGE
EXACT IMPLEMENTATION OF DESIGN PATTERNS IN C# LANGUAGE
ijait
 
Module 4: UML In Action - Design Patterns
Module 4:  UML In Action - Design PatternsModule 4:  UML In Action - Design Patterns
Module 4: UML In Action - Design Patterns
jaden65832
 
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Isuru Perera
 
Design patterns
Design patternsDesign patterns
Design patterns
Vignesh Nethaji
 
Design Patterns Java programming language.pdf
Design Patterns Java programming language.pdfDesign Patterns Java programming language.pdf
Design Patterns Java programming language.pdf
totallyrealmail420
 
Design pattern
Design patternDesign pattern
Design pattern
Thibaut De Broca
 
software engineering Design Patterns.pdf
software  engineering Design   Patterns.pdfsoftware  engineering Design   Patterns.pdf
software engineering Design Patterns.pdf
mulugetaberihun3
 
Gang of Four in Java
Gang of Four in Java Gang of Four in Java
Gang of Four in Java
Mina Tafreshi
 
Style & Design Principles 02 - Design Patterns
Style & Design Principles 02 - Design PatternsStyle & Design Principles 02 - Design Patterns
Style & Design Principles 02 - Design Patterns
Nick Pruehs
 
Architecture and design
Architecture and designArchitecture and design
Architecture and design
himanshu_airon
 
Design pattern of software words computer .pptx
Design pattern of software words computer .pptxDesign pattern of software words computer .pptx
Design pattern of software words computer .pptx
muslimpari2503
 
3.3 programming fundamentals
3.3 programming fundamentals3.3 programming fundamentals
3.3 programming fundamentals
Sayed Ahmed
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
Prophecy Of Design Patterns
Prophecy Of Design PatternsProphecy Of Design Patterns
Prophecy Of Design Patterns
pradeepkothiyal
 
M04_DesignPatterns software engineering.ppt
M04_DesignPatterns software engineering.pptM04_DesignPatterns software engineering.ppt
M04_DesignPatterns software engineering.ppt
ssuser2d043c
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
Mohammad Shaker
 
EXACT IMPLEMENTATION OF DESIGN PATTERNS IN C# LANGUAGE
EXACT IMPLEMENTATION OF DESIGN PATTERNS IN C# LANGUAGEEXACT IMPLEMENTATION OF DESIGN PATTERNS IN C# LANGUAGE
EXACT IMPLEMENTATION OF DESIGN PATTERNS IN C# LANGUAGE
ijait
 
Module 4: UML In Action - Design Patterns
Module 4:  UML In Action - Design PatternsModule 4:  UML In Action - Design Patterns
Module 4: UML In Action - Design Patterns
jaden65832
 
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Unified Modeling Language (UML), Object-Oriented Programming Concepts & Desig...
Isuru Perera
 
Design Patterns Java programming language.pdf
Design Patterns Java programming language.pdfDesign Patterns Java programming language.pdf
Design Patterns Java programming language.pdf
totallyrealmail420
 
software engineering Design Patterns.pdf
software  engineering Design   Patterns.pdfsoftware  engineering Design   Patterns.pdf
software engineering Design Patterns.pdf
mulugetaberihun3
 
Gang of Four in Java
Gang of Four in Java Gang of Four in Java
Gang of Four in Java
Mina Tafreshi
 
Style & Design Principles 02 - Design Patterns
Style & Design Principles 02 - Design PatternsStyle & Design Principles 02 - Design Patterns
Style & Design Principles 02 - Design Patterns
Nick Pruehs
 
Architecture and design
Architecture and designArchitecture and design
Architecture and design
himanshu_airon
 
Design pattern of software words computer .pptx
Design pattern of software words computer .pptxDesign pattern of software words computer .pptx
Design pattern of software words computer .pptx
muslimpari2503
 
3.3 programming fundamentals
3.3 programming fundamentals3.3 programming fundamentals
3.3 programming fundamentals
Sayed Ahmed
 
Ad

More from Jieyi Wu (8)

Design pattern advanced ii with testing
Design pattern advanced ii with  testingDesign pattern advanced ii with  testing
Design pattern advanced ii with testing
Jieyi Wu
 
Design pattern advanced i
Design pattern advanced iDesign pattern advanced i
Design pattern advanced i
Jieyi Wu
 
Dependency injection
Dependency injectionDependency injection
Dependency injection
Jieyi Wu
 
Application architecture pattern
Application architecture patternApplication architecture pattern
Application architecture pattern
Jieyi Wu
 
Reactive X introduction part1
Reactive X introduction part1Reactive X introduction part1
Reactive X introduction part1
Jieyi Wu
 
Karitoke's supported technology
Karitoke's supported technologyKaritoke's supported technology
Karitoke's supported technology
Jieyi Wu
 
Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet Kotlin
Jieyi Wu
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
Jieyi Wu
 
Design pattern advanced ii with testing
Design pattern advanced ii with  testingDesign pattern advanced ii with  testing
Design pattern advanced ii with testing
Jieyi Wu
 
Design pattern advanced i
Design pattern advanced iDesign pattern advanced i
Design pattern advanced i
Jieyi Wu
 
Dependency injection
Dependency injectionDependency injection
Dependency injection
Jieyi Wu
 
Application architecture pattern
Application architecture patternApplication architecture pattern
Application architecture pattern
Jieyi Wu
 
Reactive X introduction part1
Reactive X introduction part1Reactive X introduction part1
Reactive X introduction part1
Jieyi Wu
 
Karitoke's supported technology
Karitoke's supported technologyKaritoke's supported technology
Karitoke's supported technology
Jieyi Wu
 
Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet Kotlin
Jieyi Wu
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
Jieyi Wu
 
Ad

Recently uploaded (20)

Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
User Vision
 
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT StrategyRisk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
john823664
 
Breaking it Down: Microservices Architecture for PHP Developers
Breaking it Down: Microservices Architecture for PHP DevelopersBreaking it Down: Microservices Architecture for PHP Developers
Breaking it Down: Microservices Architecture for PHP Developers
pmeth1
 
Scientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal DomainsScientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal Domains
syedanidakhader1
 
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
Toru Tamaki
 
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
SOFTTECHHUB
 
Developing Product-Behavior Fit: UX Research in Product Development by Krysta...
Developing Product-Behavior Fit: UX Research in Product Development by Krysta...Developing Product-Behavior Fit: UX Research in Product Development by Krysta...
Developing Product-Behavior Fit: UX Research in Product Development by Krysta...
UXPA Boston
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptxIn-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
aptyai
 
TrustArc Webinar: Cross-Border Data Transfers in 2025
TrustArc Webinar: Cross-Border Data Transfers in 2025TrustArc Webinar: Cross-Border Data Transfers in 2025
TrustArc Webinar: Cross-Border Data Transfers in 2025
TrustArc
 
Building a research repository that works by Clare Cady
Building a research repository that works by Clare CadyBuilding a research repository that works by Clare Cady
Building a research repository that works by Clare Cady
UXPA Boston
 
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdfICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
Eryk Budi Pratama
 
How Top Companies Benefit from Outsourcing
How Top Companies Benefit from OutsourcingHow Top Companies Benefit from Outsourcing
How Top Companies Benefit from Outsourcing
Nascenture
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
RFID in Supply chain management and logistics.pdf
RFID in Supply chain management and logistics.pdfRFID in Supply chain management and logistics.pdf
RFID in Supply chain management and logistics.pdf
EnCStore Private Limited
 
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UXPA Boston
 
Secondary Storage for a microcontroller system
Secondary Storage for a microcontroller systemSecondary Storage for a microcontroller system
Secondary Storage for a microcontroller system
fizarcse
 
Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...
Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...
Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...
UXPA Boston
 
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Gary Arora
 
Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.
marketing943205
 
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
User Vision
 
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT StrategyRisk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
Risk Analysis 101: Using a Risk Analyst to Fortify Your IT Strategy
john823664
 
Breaking it Down: Microservices Architecture for PHP Developers
Breaking it Down: Microservices Architecture for PHP DevelopersBreaking it Down: Microservices Architecture for PHP Developers
Breaking it Down: Microservices Architecture for PHP Developers
pmeth1
 
Scientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal DomainsScientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal Domains
syedanidakhader1
 
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
論文紹介:"InfLoRA: Interference-Free Low-Rank Adaptation for Continual Learning" ...
Toru Tamaki
 
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
OpenAI Just Announced Codex: A cloud engineering agent that excels in handlin...
SOFTTECHHUB
 
Developing Product-Behavior Fit: UX Research in Product Development by Krysta...
Developing Product-Behavior Fit: UX Research in Product Development by Krysta...Developing Product-Behavior Fit: UX Research in Product Development by Krysta...
Developing Product-Behavior Fit: UX Research in Product Development by Krysta...
UXPA Boston
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptxIn-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
aptyai
 
TrustArc Webinar: Cross-Border Data Transfers in 2025
TrustArc Webinar: Cross-Border Data Transfers in 2025TrustArc Webinar: Cross-Border Data Transfers in 2025
TrustArc Webinar: Cross-Border Data Transfers in 2025
TrustArc
 
Building a research repository that works by Clare Cady
Building a research repository that works by Clare CadyBuilding a research repository that works by Clare Cady
Building a research repository that works by Clare Cady
UXPA Boston
 
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdfICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
ICDCC 2025: Securing Agentic AI - Eryk Budi Pratama.pdf
Eryk Budi Pratama
 
How Top Companies Benefit from Outsourcing
How Top Companies Benefit from OutsourcingHow Top Companies Benefit from Outsourcing
How Top Companies Benefit from Outsourcing
Nascenture
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
RFID in Supply chain management and logistics.pdf
RFID in Supply chain management and logistics.pdfRFID in Supply chain management and logistics.pdf
RFID in Supply chain management and logistics.pdf
EnCStore Private Limited
 
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UXPA Boston
 
Secondary Storage for a microcontroller system
Secondary Storage for a microcontroller systemSecondary Storage for a microcontroller system
Secondary Storage for a microcontroller system
fizarcse
 
Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...
Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...
Bridging AI and Human Expertise: Designing for Trust and Adoption in Expert S...
UXPA Boston
 
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Harmonizing Multi-Agent Intelligence | Open Data Science Conference | Gary Ar...
Gary Arora
 
Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.
marketing943205
 

Design pattern part 2 - structural pattern

  • 2. GoF Design Pattern × Creational Patterns × Structural Patterns × Behavioral Patterns 1
  • 3. Structural Pattern 2 × Adapter × Bridge × Composite × Decorator × Facade × Flyweight × Proxy
  • 6. Roles of the pattern × Target × Adaptee × Adapter 5
  • 7. Target 6 interface IMinion { void DoAttack(); void DoDefense(); } class Captain implements IMinion { @Override public void DoAttack() { // Do Captain attack. } @Override public void DoDefense() { // Do Captain defense. } } class Rookie implements IMinion { @Override public void DoAttack() { // Do Rookie attack. } @Override public void DoDefense() { // Do Rookie defense. } }
  • 8. Adaptee 7 interface IEnemy { void DoFire(); void DoGuard(); } class Boss implements IEnemy { @Override public void DoFire() { // Do something. } @Override public void DoGuard() { // Do something. } }
  • 9. Adaptor 8 class AdapterMinion implements IMinion { private final IEnemy iEnemy; AdapterMinion(IEnemy iEnemy) { this.iEnemy = iEnemy; } @Override public void DoAttack() { iEnemy.DoFire(); } @Override public void DoDefense() { iEnemy.DoGuard(); } }
  • 10. Client 9 public class Client { static public void main(String[] args) { IMinion rookie = new Rookie(); rookie.DoAttack(); IMinion enemy = new AdapterMinion(new Boss()); enemy.DoAttack(); enemy.DoDefense(); } }
  • 11. 10
  • 12. Pros. & Cons. ✓ Though the adapter, the original code isn’t modified. ✓ Expandable and adaptable, following OCP(Open Close Principle). ✓ For client, clear; For adapter, reusable. ✗ It unnecessarily increases the size of the code as class inheritance is less used and lot of code is needlessly duplicated between classes. 11
  • 13. 2. Bridge Pattern 12 12 • Separates an object’s interface from its implementation
  • 15. Roles of the pattern × Abstraction × Refined Abstraction × Implementor × Concrete Implementor 14
  • 16. Abstraction 15 abstract class IMinion { protected final IWeapon weapon; protected IMinion(IWeapon weapon) { this.weapon = weapon; } abstract void DoAttack(); }
  • 17. Refined Abstraction 16 class Solider extends IMinion { protected Solider(IWeapon weapon) { super(weapon); } @Override void DoAttack() { weapon.Fire(); } } class Enemy extends IMinion { protected Enemy(IWeapon weapon) { super(weapon); } @Override void DoAttack() { weapon.Fire(); } }
  • 19. Concrete Implementor 18 class Gun implements IWeapon { @Override public void Fire() { // Shoot operation. } } class Rocket implements IWeapon { @Override public void Fire() { // Fire operation. } }
  • 20. Client 19 public class Client { static public void main(String[] args) { IMinion solider = new Solider(new Rocket()); solider.DoAttack(); IMinion enemy = new Enemy(new Gun()); enemy.DoAttack(); } }
  • 21. 20
  • 22. Pros. & Cons. ✓ Decouple the interface & the implement. ✓ Improving the expandability of the system, but anti SRP. ✓ This pattern is diaphanous for Client and hide the detail. ✗ The system becomes complexity and incomprehensible. 21
  • 23. 3. Composite Pattern • A tree structure of simple and composite objects 22
  • 25. Roles of the pattern × Component × Leaf × Composite 24
  • 26. Component 25 abstract class MenuComponent { public void add(MenuComponent menuComponent) { throw new UnsupportedOperationException(); } public void remove(MenuComponent menuComponent) { throw new UnsupportedOperationException(); } public MenuComponent getChild(int i) { throw new UnsupportedOperationException(); } public String getName() { throw new UnsupportedOperationException(); } public String getDescription() { throw new UnsupportedOperationException(); } public double getAttackValue() { throw new UnsupportedOperationException(); } public double getDefenseValue() { throw new UnsupportedOperationException(); } }
  • 27. Composite 26 class Menu extends MenuComponent { private final String name; private final String description; private ArrayList components = new ArrayList<MenuComponent>(); Menu(String name, String description) { this.name = name; this.description = description; } @Override public void add(MenuComponent menuComponent) { components.add(menuComponent); } @Override public void remove(MenuComponent menuComponent) { components.remove(menuComponent); } @Override public MenuComponent getChild(int i) { return (MenuComponent) components.get(i); } @Override public String getName() {return name;} @Override public String getDescription() {return description;} }
  • 28. Leaf 27 class MenuItem extends MenuComponent { private String name; private String description; private final double attack; private final double defense; MenuItem(String name, String description, double attack, double defense) { this.name = name; this.description = description; this.attack = attack; this.defense = defense; } @Override public String getName() {return name;} @Override public String getDescription() {return description;} @Override public double getAttackValue() {return attack;} @Override public double getDefenseValue() {return defense;} }
  • 29. Client 28 public class Client { static public void main(String[] args) { MenuComponent weaponMenu = new Menu("Weapon", "Hero's weapon menu"); MenuComponent clothMenu = new Menu("Cloth", "Hero's cloth menu"); MenuComponent trouserMenu = new Menu("Trouser", "Hero's armor menu"); MenuComponent all = new Menu("Root menu", "Top"); all.add(weaponMenu); all.add(clothMenu); all.add(trouserMenu); weaponMenu.add(new MenuItem("Sword", "Sword", 10, 0)); weaponMenu.add(new MenuItem("Blade", "Blade", 6, 0)); weaponMenu.add(new MenuItem("Axe", "Axe", 14, 3)); clothMenu.add(new MenuItem("Cloth", "Cloth", 0, 6)); clothMenu.add(new MenuItem("Magic Cloth", "Magic Cloth", 0, 3)); clothMenu.add(new MenuItem("Knight Armor", "Knight Armor", 0, 10)); trouserMenu.add(new MenuItem("Trouser", "Trouser", 0, 10)); trouserMenu.add(new MenuItem("Knight Pants", "Knight Pants", 0, 4)); trouserMenu.add(new MenuItem("Underwear", "Underwear", 0, 8)); } }
  • 30. 29
  • 31. ✓ Separating the layer objects and adding a new object easily. ✓ Client can operate leaves & composite object consistently. ✓ Adding a new composite object easily. ✗ Design will be more abstract. Pros. & Cons. 30
  • 34. Roles of the pattern × Component × Concrete Component × Decorator × Concrete Decorator 33
  • 35. Component 34 interface IWeapon { float attack = 0; float defense = 0; float currentAttack(); float currentDefense(); }
  • 36. Concrete Component 35 class Sword implements IWeapon { float attack = 10; float defense = 0; @Override public float currentAttack() { return attack; } @Override public float currentDefense() { return defense; } } class Axe implements IWeapon { float attack = 15; float defense = 5; @Override public float currentAttack() { return attack; } @Override public float currentDefense() { return defense; } }
  • 37. Decorator 36 abstract class Decorator implements IWeapon { private final IWeapon weapon; Decorator(IWeapon weapon) { this.weapon = weapon; } @Override public float currentAttack() { return weapon.currentAttack(); } @Override public float currentDefense() { return weapon.currentDefense(); } }
  • 38. Concrete Decorator 37 class ThunderDecorator extends Decorator { ThunderDecorator(IWeapon weapon) { super(weapon); } @Override public float currentAttack() { return super.currentAttack() + 15; } @Override public float currentDefense() { return super.currentDefense() + 5; } } class FireDecorator extends Decorator { FireDecorator(IWeapon weapon) { super(weapon); } @Override public float currentAttack() { return super.currentAttack() + 10; } @Override public float currentDefense() { return super.currentDefense(); } }
  • 39. Concrete Decorator 38 class PoisonDecorator extends Decorator { PoisonDecorator(IWeapon weapon) { super(weapon); } @Override public float currentAttack() { return super.currentAttack() + 20; } @Override public float currentDefense() { return super.currentDefense(); } }
  • 40. Client 39 public class Client { static public void main(String[] args) { IWeapon powerSword = new FireDecorator( new PoisonDecorator(new Sword())); IWeapon magicAxe = new ThunderDecorator( new FireDecorator(new Axe())); } }
  • 41. Pros. & Cons. 40 ✓ Decorator is more flexible than inheritance. ✓ Decorator can expand the functions of an object. ✓ Decorators of them combined can create various objects. ✓ Following the OCP(Open Closed Principle). ✗ Because when using the decorator pattern, there’re many objects are created. ✗ It becomes more difficult to debug.
  • 42. 5. Facade Pattern • A single class that represents an entire subsystem 41
  • 44. Role of the pattern × Façade × SubSystems 43
  • 45. Subsystem 44 class WarriorRoles {} class MagicianRoles {} class HunterRoles {} class KnightRoles {} class Minions {}
  • 46. Facade 45 class Stage { private final WarriorRoles warriorRoles; private final MagicianRoles magicianRoles; private final HunterRoles hunterRoles; private final KnightRoles knightRoles; private final Minions minions; Stage(WarriorRoles warriorRoles, MagicianRoles magicianRoles, HunterRoles hunterRoles, KnightRoles knightRoles, Minions minions) { this.warriorRoles = warriorRoles; this.magicianRoles = magicianRoles; this.hunterRoles = hunterRoles; this.knightRoles = knightRoles; this.minions = minions; } public void StageIce() { warriorRoles.off(); magicianRoles.off(); hunterRoles.on(); knightRoles.off(); minions.quantity(200); } public void StageAirCastle() { warriorRoles.on(); magicianRoles.off(); hunterRoles.off(); knightRoles.on(); minions.quantity(1000); } }
  • 47. Client 46 public class Client { static public void main(String[] args) { Stage stage = new Stage(new WarriorRoles(), new MagicianRoles(), new HunterRoles(), new KnightRoles(), new Minions()); stage.StageIce(); stage.StageAirCastle(); } }
  • 48. Pros. & Cons. ✓ Reducing the dependency between the subsystem. ✓ Doesn’t have to care about the subsystem. ✓ Providing only one entry for using the object. ✗ If Client cant constrain to use subsystem well, it will decrease the flexibility and variability. ✗ Anti OCP(Open Closed Principle). 47
  • 49. 6. Flyweight Pattern • A fine-grained instance used for efficient sharing 48
  • 51. Role of the pattern × Flyweight × Concrete Flyweight × Flyweight Factory × Client 50
  • 52. Flyweight 51 abstract class Flyweight { abstract void plant(int x, int y); }
  • 53. Concrete Flyweight 52 class Tree extends Flyweight { private int pX = 0, pY = 0; private int height = 100; private double leafQuantity = 0.7f; private int leafColor = 0x1100ff; @Override void plant(int x, int y) { pX = x; pY = y; // Do something. } } class Grass extends Flyweight { private int pX = 0, pY = 0; private double leafQuantity = 0.2f; private int leafColor = 0x0000ff; @Override void plant(int x, int y) { pX = x; pY = y; // Do something. } }
  • 54. Flyweight Factory 53 class FlyweightFactory { private final HashMap<String, Flyweight> pool = new HashMap<>(); public Flyweight getFlyweight(String key) { if (null == pool.get(key)) { Flyweight object; if (Objects.equals("grass", key)) { object = new Grass(); } else if (Objects.equals("tree", key)) { object = new Tree(); } pool.put(key, object); } return pool.get(key); } public int getFlyweightCount() { return pool.size(); } }
  • 55. Client 54 public class Client { static public void main(String[] args) { FlyweightFactory flyweightFactory = new FlyweightFactory(); flyweightFactory.getFlyweight("tree").plant (3, 6); flyweightFactory.getFlyweight("grass").plant (1, 3); flyweightFactory.getFlyweight("grass").plant (2, 6); flyweightFactory.getFlyweight("tree").plant (1, 0); } }
  • 56. Pros. & Cons. ✓ Reducing the objects quantity in the memory. ✓ The flyweight’s state is dependent. ✗ The system will be more complexity because separating the internal & external state. 55
  • 57. 7. Proxy Pattern • An object representing another object 56
  • 59. Role of the pattern × Subject × Proxy × RealSubject 58
  • 61. Proxy 60 class Proxy implements IAttack { private final IAttack subject; public Proxy(IAttack subject) { this.subject = subject; } @Override public void doAttack() { // Do professional attack!!! } }
  • 62. RealSubject 61 class Player implements IAttack { @Override public void doAttack() { // Do attack. } }
  • 63. Client 62 public class Client { static public void main(String[] args) { IAttack proxy = new Proxy(new Player()); proxy.doAttack(); } }
  • 64. Pros. & Cons. ✓ Hide the real subject to avoid the Client uses it directly. ✗ The operation speed will be lower. ✗ For implementing the proxy, there’re many extra works and some proxy’s implementation is really complexity. 63