Está en la página 1de 32

Design Patterns continued

Learning Goals continued


By the end of this unit, you will be able to:
Clearly and concisely describe, give examples of
software situations in which youd use, explain the
key benefit of, and drawbacks or special
considerations for the following patterns: factory
method, builder, decorator

Creational Patterns

Abstract Factory (last class)


Singleton (last class and review from 210)
Builder
Factory Method

Factory Method
Intent:
Want to hide the details of sub-class specific
implementations from Client
A simplified Abstract Factory where families of related
objects are not relevant
Two kinds:
Polymorphic (by inheritance)
We already saw this in the Abstract Factory

Discriminator (by argument)


A simplified version

Factory Method by Inheritance

Compare this to Abstract Factory

Factory Method by Discriminator


A simpler version:
Want to hide concrete class from client but there
is only one product interface
The types of sub-classes are known in advance
and can be hard-coded in the super-class

public abstract class Pizza {


public static Pizza createPizza(String type) {
Pizza pizza = null;
if (type.equals("cheese")) {
pizza = new CheesePizza();
} else if (type.equals("pepperoni")) {
pizza = new PepperoniPizza();
} else if (type.equals("veggie")) {
pizza = new VeggiePizza();
}
return pizza;
}
}

Important Design Decisions


Will there ever be more types of Pizzas?
If not, then discriminator is good choice
Recall Extreme Programming Rule:
Simple Design

If so, is the person who wrote the Pizza class the


same person who will add new types of Pizzas?
If not, then inheritance is better
Wont require modification to Pizza class

Builder (Creational pattern)


Intent: Separate the construction of a complex object from
its representation so that the same construction process
can create different representations
Use the Builder pattern when:
the algorithm for creating a complex object should be
independent of the parts that make up the object and how
they are assembled
the construction process must allow different representations
for the object that is constructed
Reference: Design Patterns, Gamma, et. al., Addison Wesley, 1995, pp 97-98

Builder Metaphor

UML Structure

Collaborations

Builder Example Code (online)


Web application needs to retrieve data about a
specific Person by id
Person data is constructed through database
operations
Data should be returned in different formats (i.e.
representations)
XML
JSON
etc

 Want to separate
database interactions (Director)
from the specific formats (Builder)

JSON Person representation


{"person":
{"address":
{"street":"2366 MainMall",
city":"Vancouver"},
name":"Terry
}
}

XML Person representation


<person>
<name>Terry</name>
<address>
<street>2366 Main Mall</street>
<city>Vancouver</city>
</address>
</person>

What is the difference between Builder and


Abstract Factory?
Why is it PersonBuilder not PersonFactory?
Why is there a Director?

Creational Patterns Summary


Abstract Factory
hide the details of sub-class specific implementations
from Client
enforce creation of related family objects

Factory Method
hide the details of sub-class specific implementations
from Client
inheritance or discriminator

Builder
Multi-step object creation
Separate the construction steps from the low-level
representation of the constructed object

Structural Patterns
Adapter (last class)
Composite (last class and review from 210)
Decorator (today and may be review from
210)
Proxy

1
7

Decorators are popular in Java


BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(
new File(text) )));
A common sign that decorators are being
used

Decorator (Structural pattern)


Intent:
Client-specified customization of features for object
Attach additional responsibilities to an object
dynamically (at run-time)

Structure of Decorators: recursively wrap objects of the same interfac

composes concrete
decorators
Client

Participants
Component
the interface of a core object

Concrete component
an implementation of the component interface

Decorator
abstract class which wraps another Component

Concrete Decorator
an implementation of Decorator which adds new
behavior before/after core behavior
through delegation

optionally adds new methods/properties

Sample problem
You need to implement a point-of-sale system for
a coffee shop. The coffee shop has some basic
beverages, but customers can customize their
drinks by choosing what kind of milk they want, if
they want flavoured syrup, etc.
You could create a class for each drink, but there
are so many possible combinations that the
number of classes would quickly get out of hand.
22

Solving this problem with inheritance

23

Freeman, et al. Design Patterns, Head First

Solving this problem with Decorators

24

Freeman, et al. Design Patterns, Head First

Solving this problem with Decorators

Freeman, et al. Head First Design Patterns


25

Definition: Delegation
Class S which implements/extends type T
has a field x of type T

A method m in S calls method m on x


class S implements T {
private T x;
public void doIt() {
//Do something before
x.doIt();
//Do something after
}
}

Common Uses
Transformers
Encode/decode
Compress/decompress
Filtering

Interceptors
Logging
Alert monitoring
Security checking

Example: Extensible Console


Component
a Console interface

Concrete component
Standard output/Standard input

Decorator
wraps a Console and delegates to it

Concrete Decorator
convert to upper case
time stamped logging
etc

Code example posted on lecture notes page

Decorator activity
Draw a UML class diagram for the system on the following
slide. Use the Decorator Pattern for some classes (perhaps as
part of a pizza delivery app) .
Once youre finished drawing the UML diagram, write the
Java code to implement the system.

29

Decorator activity
1. interface PizzaOrder {
boolean isVegan(); //true if it has no cheese or meat
boolean hasMeat();
double price(); //dollars
} //Dont need a hasCheese method
2. BasicMediumPizza
A regular pizza, nothing special, costs $10.00
This pizza includes cheese by default (in real life), no need to additionally specify
cheese (in the code)
3. NoCheese: Modifies a pizza so no cheese is used at no additional charge
4. Pepperoni : Modifies a pizza so pepperoni is added, for $1.00
5. Client : Creates a basic medium pizza, no cheese, with pepperoni. Checks the price
and checks if it is vegan.
6. Do you need any other types?

30

Questions for your user stories


Given only the information on this user story,
1. Will the TA be able to verify in a demo that the
story has been implemented?
2. Can the result of testing the acceptance criteria
be verified objectively?
3. By checking the acceptance criteria, will the TA
be able to verify that the implementation has
no obvious errors (edge cases, boundary
conds.)?
4. Will my team be able to accurately estimate the
time to implement the feature (give or take a
few days)?

Questions for your user stories


5. Does the user story address a feature specific
to my application (not a generic web application
feature)?
e.g. logging in/logging out is not a necessary user
story

6. Will the implementation of the user story


allow us to demonstrate that one (or more) of
the project technical requirements is
addressed?

También podría gustarte