02 On Design Patterns
02 On Design Patterns
2022-08-31
2 / 113
Part I
Intro
3 / 113
General concept of patterns (253 of them, for architecture in the buildings sense):
Similarities between software design and architecture was noted by Smith 1987.
4 / 113
SOLID
Part III
Outline
I Strategy
I Builder
I Factory Method
I Adapter
I Decorator
I Bridge
I Template Method
I Observer
I Composite
I Chain of Responsibility
I Abstract Factory (+ Dependency
I Memento
Injection)
I Command
I Singleton (+ example in Ruby)
13 / 113
Part IV
Strategy
14 / 113
Strategy
Strategy
Context
Client
15 / 113
Strategy: Consequences
Part V
Factory Method
17 / 113
Factory method
20 / 113
Factory method
Part VI
Decorator
22 / 113
Decorator
Component
Decorator
Decorator
Part VII
Template Method
25 / 113
Template Method
class Coffee {
public :
void prepareRecipe ();
void boilWater ();
void brewCoffeeGrinds ();
class Beverage {
void pourInCup (); public :
void addSugarAndMilk (); void prepareRecipe ();
}; void boilWater ();
class Tea{ void pourInCup ();
public : // No brew == steep
void prepareRecipe (); // No addCondiments
void boilWater ();
};
void steepTeaBag ();
void pourInCup ();
void addLemon ();
};
26 / 113
Template method
28 / 113
Template method?
No
Yes
30 / 113
Part VIII
Composite
32 / 113
Waiter
Diner
menu
print() printMenu()
Pizza
menu
Breakfast
menu print()
Spam,
Clam
Pizza
Cheese
Pizza
Coffee
menu
Ham &
eggs
Spam &
eggs
Eggs &
spam
spam &
eggs
print()
Dark
roast
Coffee
Tea Espresso print()
33 / 113
34 / 113
Client
Component
Composite
Leaf
35 / 113
Composite: consequences
Part IX
Abstract Factory
37 / 113
38 / 113
39 / 113
Frozen Clam
Parmesan Cheese Chicago
Thick Crust Dough
40 / 113
41 / 113
42 / 113
43 / 113
Concrete Factory
Abstract Factory
Abstract Products
44 / 113
Clients
45 / 113
Strategy – behavioural
Abstract factory – creational
I When related classes only differ in
I A system should be independent of
behaviour
how its products are created
I You need different variants of an
I A system should be configured with
algorithm
one of multiple families of products
I An algorithm uses data the clients
I You want to provide a class library of
don’t need to know
products, and only expose their
I A class uses conditionals for selecting
interfaces
behavior
47 / 113
Part X
Dependency Injection
49 / 113
1. Dependencies
namespace DITest {
public class FancyClamPizza : IClamPizza {
private IClam clam;
private ICheese cheese ;
public FancyClamPizza ( IClam clam , ICheese cheese ) {
this.clam = clam;
this. cheese = cheese ;
}
public String ClamType () {
return String . Format ("fancy {0}",clam);
}
public String Describe () {
return String . Format ("fancy clam pizza with {0} and
{1}",ClamType () , cheese );
}
}
51 / 113
2. Registration
namespace DITest {
public class IoCInstaller : IWindsorInstaller {
public void Install ( IWindsorContainer container , IConfigurationStore
store) {
container . Register ( Classes
. FromThisAssembly ()
. InNamespace (" DITest . NYStyle ")
. WithServiceAllInterfaces ());
container . Register ( Classes
. FromThisAssembly ()
. AllowMultipleMatches ()
. InSameNamespaceAs < IoCInstaller >()
. WithServiceAllInterfaces ());
}
}
}
3. Resolution
Part XI
Singleton
54 / 113
Our app takes forever to load if the Singleton class is part of it.
55 / 113
someOtherMethod invoked
Singleton name: Anders
Singleton lookup took 1 003 348 000 ns
Static method invocation took 1 002 463 000 ns
56 / 113
private Singleton () {
try {
// Very expensive job indeed
Thread .sleep (100);
} catch ( InterruptedException e) {
e. printStackTrace ();
}
name = Math. random () > 0.5 ? " Jonas " : " Anders ";
}
Woohoo!
61 / 113
Singleton as Enum
public enum EnumSingleton {
INSTANCE ;
private String name;
private int age;
Singletons in Ruby
63 / 113
class A
end irb(main):014:0 > a
#<A:0 x007f8d6b92bcb0 >
a = A.new irb(main):016:0 > A.new
RuntimeError : Illegal !
class << A from (irb):10: in `new '
def new from (irb):16
raise " Illegal !" from ruby-2.0.0-p247 /bin/
end irb :13: in `<main >'
end
Now we have one object, but we cannot produce another of the same class
64 / 113
Singleton: consequences
Part XII
Builder
67 / 113
68 / 113
69 / 113
70 / 113
Client
Director
Builder
71 / 113
Abstract Factory
Builder
Builder: consequences
+ Can control the way objects are - Not necessarily a common interface
created for products
+ Can produce different products using - Clients must know how to initialize
the same Director builders and retrieve products
73 / 113
Part XIII
Adapter
74 / 113
Adapter
75 / 113
Class Adapter
Object Adapter
76 / 113
Adapter: consequences
Part XIV
Bridge
81 / 113
Bridge Strategy
Intent Decouple two class hierarchies (ab- Allow for exchangeable algorithms
straction/implementation)
Collaborations The Bridge forwards requests to the The Context and Strategy collabo-
Implementor rate, passing data between them
83 / 113
Bridge Adapter
Intent Decouple two class hierarchies (ab- Convert an existing class to fit a
straction/implementation) new interface
Applicability In a new system In an existing system
84 / 113
Bridge: consequences
Part XV
Observer
87 / 113
RSS feeds
88 / 113
89 / 113
90 / 113
Mediator vs Observer
Part XVI
Chain of Responsibility
94 / 113
95 / 113
96 / 113
Examples
I Logging
I Input management in GUI:s
97 / 113
Part XVII
Memento
99 / 113
Memento
100 / 113
101 / 113
Iterative Optimizer
iteration
current target value
current solution
Optimize() SolverMemento
Abort() iteration
GetState() current target value
SetState() current solution
Client
- memento
- optimizer
Optimize()
Abort()
ResetOptimizer(SolverMemento)
102 / 113
Memento: consequences
+ Can externalize object state for later restoration within the lifetime of the object
+ Encapsulates access to the objects’ inner state
- Depending on implementation, access to private fields requires memento classes
as inner/friend classes to each domain class
104 / 113
Part XVIII
Command
105 / 113
Command
106 / 113
Remote control
107 / 113
108 / 113
109 / 113
Command: consequences
Part XIX
Finishing up
111 / 113
Coursework
I Intro seminar
I Using design patterns lab (implement design in skeleton) + seminar (finished with
the lab and share solution 24h in advance)
I Design principles and Reading design patterns (next week)
113 / 113
References