(Week 8) Design Patterns and Antipatterns2
(Week 8) Design Patterns and Antipatterns2
week 8
Design patterns 2
and Anti-patterns
Types of design patterns
Creational:
- Abstracts the object instantiation
process
Structural:
- Abstracts how classes and objects are
composed to build larger structures
Behavioural:
- Abstracts algorithms and assignment of
responsibility among objects 2
Types of design patterns
Creational:
- Abstracts the object instantiation
process
Structural:
- Abstracts how classes and objects are
composed to build larger structures
Behavioural:
- Abstracts algorithms and assignment of
responsibility among objects 3
Behavioural patterns
- Chain of
Responsibility - State
- Command - Strategy
- Interpreter - Template
- Iterator Method
- Mediator - Visitor
- Memento
- Observer
Strategy
Name:
- Strategy (aka: Policy)
Problem description:
- Use to make the method by which a task is
accomplished easily replaceable
Solution description:
- New approaches to accomplishing a task
are produced by extending an abstraction
5
Strategy
6
Example: Duck simulator
7
Ducks should fly… shouldn’t
they?
• The executives want to enhance the existing
simulator with a new feature
• What is the best way to add a flying behaviour to
our duck simulator?
Add a concrete
method fly() to
the base class
8
New duck simulator
9
New duck simulator
• Ducks fly
• Duck simulator includes other types of ducks
• rubber ducks, decoy ducks, etc.
• Using a concrete method in the base class caused
side effects on some subclasses
• In other words, a bug
10
How to fix the duck simulator?
• The problem is that different ducks have different
behaviour
• Requirements are always changing
• The design is not prepared to deal with ducks
having different types of behaviors
11
How to fix the duck simulator?
12
Apply strategy pattern to duck
sim.
Fly behavior
Duck type
13
Duck simulator improved with
strategy pattern
14
Template Method
Problem description:
- Use to share common parts of an
implementation while allowing subclasses
to refine other parts
Solution description:
- Common parts are defined in the
superclass, which makes calls to abstract
methods that deliver the other parts
15
Template Method
16
Example: Coffee shop
17
Initial design
18
Design improved using
template method
19
Types of design patterns
Creational:
- Abstracts the object instantiation
process
Structural:
- Abstracts how classes and objects are
composed to build larger structures
Behavioural:
- Abstracts algorithms and assignment of
responsibility among objects 20
Structural patterns
Structural patterns:
- Adapter
- Bridge
- Composite
- Decorator
- Façade
- Flyweight
- Proxy
21
Structural patterns
Structural patterns:
- Adapter
- Bridge
- Composite
- Decorator
- Façade
- Flyweight
- Proxy
22
Adapter
Name:
- Adapter (aka: Wrapper)
Problem description:
- Use when a class’ interface doesn’t match
with the hierarchy that we want to use
Solution description:
- Inject a class to adapt the interface to the
expectation
23
Adapter pattern example
• If it walks like a duck and quacks like a duck, then it must might be a duck
turkey wrapped with a duck adapter...
public class MallardDuck implements Duck { public class WildTurkey implements Turkey {
public void quack() { public void gobble() {
System.out.println("Quack"); System.out.println("Gobble gobble");
} }
24
The problem
• Now, let’s say you’re short on Duck objects and
you’d like to use some Turkey objects in their place.
• Obviously, we can’t use the turkeys outright
because they have a different interface
• Let’s write an Adapter:
25
Code example: Adapter
26
code example: driver class
public class DuckTestDrive {
public static void main(String[] args) {
MallardDuck duck = new MallardDuck();
27
Structural patterns
Structural patterns:
- Adapter
- Bridge
- Composite
- Decorator
- Façade
- Flyweight
- Proxy
28
Decorator
Name:
- Decorator
Problem description:
- Add additional responsibility to an object
dynamically. An alternative to subclassing.
Solution description:
- Use an abstraction to inject added
behaviour dynamically
29
Decorator
Beverage
-description
getDescription()
cost()
31
Problem
• In addition to your coffee, you can also ask for
several condiments like steamed milk, soy, and
mocha, and have it all topped off with whipped
milk.
• The coffee shop charges a bit for each of these, so
they really need to get them built into their order
system.
32
Applying decorator pattern to
coffee shop
component
Beverage
-description
getDescription()
cost()
concrete components
33
Code example: Component and
Concrete Component
34
Code example: Decorator and
Concrete Decorator
35
Watch out
for over-
engineering!
Overuse of design
patterns can
cause system
bloat!
36
Avoiding over-engineering
37
Desirable design properties:
Cohesion and Coupling
Cohesion:
- Degree to which a module relies on
other members within the module to
deliver its functionality
- Desirable to keep HIGH
Coupling:
- Degree to which a module relies on
other modules to deliver functionality
- Desirable to keep LOW 38
Which pattern to choose?
https://forms.office.com/r/jcjJK7GMY1 39
Design anti-patterns
40
Anti-patterns and code smells
- Blob - Duplicate
- Spaghetti Code code
- Functional decomposition- Feature envy
- Swiss army knife - Long method
- Long
parameter list
- Lazy class
What is a design anti-pattern?
Problem description:
- Useful pieces of code are copy-pasted
throughout the codebase
Solution description:
- Use an abstraction technique (e.g.,
method, inheritance) to refactor the code
43
Code Duplication
// Original code
public int calculateAreaOfRectangle(int length, int
width) {
return length * width;
}
// Duplicated code
public int calculateAreaOfSquare(int sideLength) {
return sideLength * sideLength;
}
44
Code Duplication
?
public int calculateAreaOfRectangle(int length, int
er
width) {
return length * width;
ett
}
tb
public int calculateVolumeOfBox(int length, int
width, int height) {
return length * width * height;
ei
}
ak
public int calculateAreaOfSquare(int sideLength) {
return calculateAreaOfRectangle(sideLength,
em
sideLength);
}
nw
sideLength);
}
45
Blob
Name:
- Blob (aka: god class)
Problem description:
- A large class that is lacking cohesion or
makes most of the processing decisions
Solution description:
- Refactor Blob classes into a series of more
cohesive classes
46
Example of anti-pattern: Blob
https://sourcemaking.com/antipatterns/the-blob
47
Spaghetti Code
• Spaghetti Code appears as a
program or system that
contains very little software
structure
• Coding and progressive
extensions compromise the
software structure to such an
extent that the structure lacks
clarity, even to the original
developer
48
Symptoms:
• Classes and Methods are process-oriented, and
named after the process, e.g., class
FileUploadProcess,
UserRegistrationProcess, etc.
• Minimal relationships exist between objects
• Object Methods have no parameters, and make use
of class or global variables
• Benefits of object orientation are lost (no
inheritance, and no polymorphism)
49
C example: Linux SCSI driver
wait_nomsg: TCM_SYNC:
if ((inb(tmport) & 0x04) != 0) { /* ... */
goto wait_nomsg; small_id:
} m = 1;
outb(1, 0x80); m <<= k;
udelay(100); if ((m & assignid_map) == 0) {
for (n = 0; n < 0x30000; n++) { goto G2Q_QUIN;
if ((inb(tmport) & 0x80) != 0) { /* bsy ? */ }
goto wait_io; if (k > 0) {
} k--;
} goto small_id;
goto TCM_SYNC; }
wait_io: G2Q5: /* srch from max acceptable ID# */
for (n = 0; n < 0x30000; n++) { k = i; /* max acceptable ID# */
if ((inb(tmport) & 0x81) == 0x0081) { G2Q_LP:
goto wait_io1; m = 1;
} m <<= k;
} if ((m & assignid_map) == 0) {
goto TCM_SYNC; goto G2Q_QUIN;
wait_io1: }
inb(0x80); if (k > 0) {
val |= 0x8003; /* io,cd,db7 */ k--;
outw(val, tmport); goto G2Q_LP;
inb(0x80); }
val &= 0x00bf; /* no sel */ G2Q_QUIN: /* k=binID#, */
outw(val, tmport);
outb(2, 0x80); https://stackoverflow.com/a/195559 50
51
References
• Ch. 1,3,7,8, Freeman, Eric, et al. Head First Design
Patterns: A Brain-Friendly Guide. " O'Reilly Media,
Inc.", 2004.
• Source Making, Anti-patterns.
https://sourcemaking.com/antipatterns/software-d
evelopment-antipatterns
52