0% found this document useful (0 votes)
17 views

(Week 8) Design Patterns and Antipatterns2

Uploaded by

spamismywaifu
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

(Week 8) Design Patterns and Antipatterns2

Uploaded by

spamismywaifu
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

SOEN 341

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?

• Two possible ways


• Override the fly() method in the rubber duck
• Make a flyable() interface with a fly (method)

12
Apply strategy pattern to duck
sim.

Fly behavior

Duck type

Fly with wings No Fly

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...

Now it’s time to meet the newest fowl on the block:

public interface Duck { public interface Turkey {


public void quack(); public void gobble();
public void fly(); public void fly();
} }

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");
} }

public void fly() { public void fly() {


System.out.println("I'm flying"); System.out.println("I'm flying a short distance");
} }
} }

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

public class TurkeyAdapter implements Duck {


Turkey turkey;

public TurkeyAdapter(Turkey turkey) {


this.turkey = turkey;
}

public void quack() {


turkey.gobble();
}

public void fly() {


for(int i=0; i < 5; i++) {
turkey.fly();
}
}
}

26
code example: driver class
public class DuckTestDrive {
public static void main(String[] args) {
MallardDuck duck = new MallardDuck();

WildTurkey turkey = new WildTurkey();


Duck turkeyAdapter = new TurkeyAdapter(turkey);

System.out.println("The Turkey says...");


turkey.gobble();
turkey.fly();

System.out.println("\nThe Duck says...");


testDuck(duck);

System.out.println("\nThe TurkeyAdapter says...");


testDuck(turkeyAdapter);
}

static void testDuck(Duck duck) {


duck.quack();
duck.fly();
}
}

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

Decorator should take in


Component in the constructor
in order to decorate it

Component c= new ConcreteComponent();


c.Operation();
c=new ConcreateDecoratorB(c); Run-time
30
c.Operation();
Decorator pattern example:
Coffee shop

Beverage
-description
getDescription()
cost()

HouseBlend DarkRoast Decaf

cost() cost() 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

HouseBlend DarkRoast Decaf CondimentDecorator


decorator

cost() cost() cost() getDescription()

Mocha Milk Whip


concrete decorators
Beverage beverage Beverage beverage Beverage beverage
cost() cost() cost()
getDescription() getDescription() getDescription()

33
Code example: Component and
Concrete Component

public abstract class Beverage { public class DarkRoast extends Beverage {


String description = "Unknown Beverage"; public DarkRoast() {
public String getDescription() { description = "Dark Roast Coffee";
return description; }
}
public double cost() {
public abstract double cost(); return .99;
} }
}

34
Code example: Decorator and
Concrete Decorator

public abstract class CondimentDecorator public class Mocha extends CondimentDecorator {


extends Beverage public Mocha(Beverage beverage) {
{ this.beverage = beverage;
Beverage beverage; }
public abstract String getDescription();
} public String getDescription() {
return beverage.getDescription() +
", Mocha";
}

public double cost() {


return .20 + beverage.cost();
}
}

35
Watch out
for over-
engineering!

Overuse of design
patterns can
cause system
bloat!

36
Avoiding over-engineering

Follow the YAGNI principle!


- “You Aren’t Going to Need It”
- Design for the system you need today
- Revisit design periodically for
opportunities to refactor and improve

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?

Anti-patterns and “code smells”:


- Are the opposite of a design
patterns
- Identify poor solutions to
recurring design problems
- Are symptoms of poor design
choices
42
Code Duplication

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;
}

public int calculateVolumeOfBox(int length, int


width, int height) {
return length * width * height;
}

// Duplicated code
public int calculateAreaOfSquare(int sideLength) {
return sideLength * sideLength;
}

public int calculateVolumeOfCube(int sideLength) {


return sideLength * 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

public int calculateVolumeOfCube(int sideLength) {


return
calculateVolumeOfBox(sideLength, sideLength,
Ca

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

You might also like