GoF Design Pattern Categories - emadilms.iremadilms.ir/emadi/wp-content/uploads/2015/02/... ·...
Transcript of GoF Design Pattern Categories - emadilms.iremadilms.ir/emadi/wp-content/uploads/2015/02/... ·...
GoF Design Pattern CategoriesPurpose
Creational Structural Behavioral
Scope Class Factory Method Adapter Interpreter
Template Method
Object Abstract Factory
Builder
Prototype
Singleton
Adapter
Bridge
Composite
Decorator
Facade
Proxy
Flyweight
Chain of Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
1
BUILDER
(Object Creational)●Intent:
Separate the construction of a complex object from
its representation so that the same construction
process can create different representations
Builders specify abstract
interfaces for creating parts
of a Product object
2
BUILDER
(Object Creational)
Usage:
Rarely used, only useful if complex objects
consisting of multiple parts need to be constructed
(composite objects for example)
3
BUILDER
(Object Creational)
●Motivation:
oRTF reader should be able to convert RTF to many
text format
oAdding new conversions without modifying the
reader should be easy
4
Builder Motivation
Each kind of converter class takes the mechanism for creating and
assembling a complex object and puts it behind an abstract
interface.
The converter is separate from the reader, which is responsible for
parsing an RTF document.
The Builder pattern captures all these relationships.
Each converter class is called a builder in the pattern, and the
reader is called the director.
5
Builder motivation
6
Builder motivation (example)
7
Builder Motivation
Applied to this example, the Builder pattern separates the
algorithm for interpreting a textual format (that is, the parser for
RTF documents) from how a converted format gets created and
represented.
This lets us reuse the RTFReader's parsing algorithm to create
different text representations from RTF documents—just
configure the RTFReader with different subclasses of
Textconverter.
8
Applicability
●Use the Builder pattern when
oThe algorithm for creating a complex object should
be independent of the parts that make up the object
and how they are assembled
oThe construction process must allow different
representations for the object that is constructed
9
Director
Construct ()
for all objects in structure
{
builder->BuildPart ()
}
Builder
BuildPart ()
ConcreteBuilder
BuildPart ()
GetResult ()
Product
builders
BUILDER
Structure
10
Builder - participants
• Builder (TextConverter):
• - specifies an abstract interface for creating parts of a
Product object.
• ConcreteBuilder (ASCIIConverter, TeXConverter,
TextWidgetConverter)
• - constructs and assembles parts of the product by
implementing the Builder interface.
• - defines and keeps track of the representation it creates.
• - provides an interface for retrieving the product (e.g.,
GetASCIIText, Get-TextWidget).
11
Builder - participants
Director (RTFReader)
- constructs an object using the Builder interface.
• Product (ASCIIText, TeXText, TextWidget)
- represents the complex object under construction.
ConcreteBuilder builds the product's internal
representation and defines the process by which it's
assembled.
- includes classes that define the constituent parts, including
interfaces for assembling the parts into the final result.
12
Builder - Collaborations
●Client creates Director object and configures it with the
desired Builder object
●Director notifies Builder whenever a part of the product
should be built
●Builder handles requests from the Director and adds parts
to the product
●Client retrieves the product from the Builder
13
Builder - Collaborations
14
Consequences
●It lets you vary a product's internal representation.
●It isolates code for construction and representation.
●It gives you finer control over the construction
process.
15
Implementation issues
●Assembly and construction interface.
●Why no abstract class for products?
●Empty methods as default in Builder.
16
Related Patterns
●Abstract Factory is similar to Builder in that it too
may construct complex objects.
●The primary difference is that the Builder pattern
focuses on constructing a complex object step by
step.
●Abstract Factory's emphasis is on families of product
objects (either simple or complex).
17
Related Patterns
●Builder returns the product as a final step, but as far
as the Abstract Factory pattern is concerned, the
product gets returned immediately.
●A Composite is what the builder often builds.
18
Known Uses
●RTF converter application is from ET++.
●Builder is a common pattern in Smalltalk-80.
The Service Configurator framework from the Adaptive
Communications Environment uses a builder to
construct network service components that are linked
into a server at run-time.
19
20
A scenario
You’ve just been asked to build a vacation planner for
Patternsland, a new theme park just outside of
Objectville. Park guests can choose a hotel and various
types of admission tickets, make restaurant
reservations, and even book special events.
To create a vacation planner, you need to be able to
create structures like this:
21
22
23
24
enum VehicleType
{ Car, MotorCycle}
------------------------------------------------
enum Wheels
{Wheels_2, Wheels_3, Wheels_4 }
-----------------------------------------
enum Door
{ Door_0, Door_2, Door_4}
----------------------------------
enum Frame
{ Car_Frame, MotorCycle_Frame }
-------------------------
enum Engine
{ Car_Engine_2500CC, MotorCycle_Engine_50CC} 26
class Vehicle //product
{
public Vehicle(VehicleType VType)
{ this.VType = VType; }
public VehicleType VType;
public Engine engin;
public Wheels wheels;
public Door door;
public Frame frame;
}
27
abstract class VehicleBuilder
{
protected Vehicle NewVehicle;
public Vehicle GetVehicle()
{ return NewVehicle; }
public abstract void BuildFrame();
public abstract void BuildWheels();
public abstract void BuildDoor();
public abstract void BuildEngine();
}
28
class CarBuilder:VehicleBuilder //concrete builder
{
public CarBuilder()
{ NewVehicle = new Vehicle(VehicleType.Car); }
public override void BuildDoor()
{ NewVehicle.door = Door.Door_4; }
public override void BuildFrame()
{ NewVehicle.frame = Frame.Car_Frame; }
public override void BuildWheels()
{ NewVehicle.wheels = Wheels.Wheels_4; }
public override void BuildEngine()
{ NewVehicle.engin = Engine.Car_Engine_2500CC; }
}
29
class MotorCycle:VehicleBuilder
{
public MotorCycle()
{ NewVehicle = new Vehicle(VehicleType.MotorCycle); }
public override void BuildDoor()
{ NewVehicle.door = Door.Door_0; }
public override void BuildEngine()
{ NewVehicle.engin = Engine.MotorCycle_Engine_50CC; }
public override void BuildWheels()
{ NewVehicle.wheels = Wheels.Wheels_2; }
public override void BuildFrame()
{ NewVehicle.frame = Frame.MotorCycle_Frame;
}
}30
class Shop //director
{
public void ConStruct(VehicleBuilder VB)
{
VB.BuildFrame();
VB.BuildEngine();
VB.BuildWheels();
VB.BuildDoor();
}
}
31
private void button1_Click(object sender, EventArgs e)
{
VehicleBuilder builder = new CarBuilder();
Shop shop = new Shop();
shop.ConStruct(builder);
Vehicle c = builder.GetVehicle();
MessageBox.Show(c.VType.ToString()); //output=car
}
32
FACTORY METHOD
(Class Creational)
● Intent:
oDefine an interface for creating an object, but let subclasses decide
which class to instantiate.
oFactory Method lets a class defer instantiation to subclasses.
● Also Known As
● Virtual Constructor
33
FACTORY METHOD
(Class Creational)
● Usage:
● Frequently used, fairly easy to implement and useful for centralizing
object lifetime management and avoiding object creation code
duplication
34
FACTORY METHOD
(Class Creational)
● Motivation:
oFramework use abstract classes to define and maintain relationships
between objects
oFramework has to create objects as well - must instantiate classes
but only knows about abstract classes - which it cannot instantiate
oFactory method encapsulates knowledge of which subclass to
create - moves this knowledge out of the framework
35
docsDocument
Open()
Close()
Save()
Revert()
Application
MyDocument
CreateDocument()
NewDocument()
OpenDocument()
MyApplication
CreateDocument()
Document* doc=CreateDocument();
docs.Add(doc);
doc->Open();
return new MyDocument
FACTORY METHOD
Motivation
36
Applicability
●Use the Factory Method pattern when
oa class can´t anticipate the class of objects it must create.
oa class wants its subclasses to specify the objects it
creates.
oclasses delegate responsibility to one of several helper
subclasses, and you want to localize the knowledge of
which helper subclass is the delegate.
37
FACTORY METHOD
(Class Creational)● structure
38
39
Participants● Product
oDefines the interface of objects the factory method creates
● ConcreteProduct
o Implements the product interface
● Creator
oDeclares the factory method which returns object of type product
oMay contain a default implementation of the factory method
oCreator relies on its subclasses to define the factory method so that
it returns an instance of the appropriate Concrete Product.
● ConcreteCreator
oOverrides factory method to return instance of ConcreteProduct
40
Collaborations
● Creator relies on its subclasses to define the factory method so that it
returns an instance of the appropriate Concrete Product.
41
Consequences
● Provides hooks for subclasses.
● Connects parallel class hierarchies.
42
Implementation
Two major varieties.
Parameterized factory methods.
Language-specific variants and issues.
Using templates to avoid subclassing.
Naming conventions.
43
Known Uses
Factory methods pervade toolkits and frameworks.
Class View in the Smalltalk-8 0Model/View/Controller
framework has a method default Controller that creates a
controller, and this might appear to be a factory method.
The Orbix ORB system from IONA Technologies uses Factory
Method to generate an appropriate type of proxy when an
object requests a reference to a remote object.
44
Related Patterns
Abstract Factory is often implemented with factory methods.
The Motivation example in the Abstract Factory pattern
illustrates Factory Method as well.
Factory methods are usually called within Template Methods.
In the document example above, NewDocument is a template
method.
45
46
Related Patterns
47
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
PROTOTYPE (Object
Creational)●Intent:
oSpecify the kinds of objects to create using a
prototypical instance, and create new objects by
copying this prototype.
●Motivation:
oFramework implements Graphic class for graphical
components and GraphicTool class for tools
manipulating/creating those components
65
Motivation
●Actual graphical components are application-specific
●How to parameterize instances of Graphic Tool class
with type of objects to create?
●Solution: create new objects in Graphic Tool by
cloning a prototype object instance
66
Tool
Manipulate()
Rotate Tool
Manipulate()
Graphic Tool
Manipulate()
Graphic
Staff MusicalNote
WholeNote
Return copy of self
HalfNotep = prototype ->Clone()
while(user drags mouse){
p ->Draw(new position)
}
Insert p into drawing
Draw(Position)
Clone()
Draw(Position)
Clone()
Draw(Position)
Clone()
Return copy of self
Draw(Position)
Clone()
prototype
PROTOTYPE
Motivation
67
PROTOTYPE
Motivation• Usage:
• Easy pattern, usage depends on the preferred software
design, provides an alternative to the other creational
patterns that are mainly based on external classes for
creation
68
Applicability
●Use the Prototype pattern when a system should be
independent of how its products are created, composed,
and represented;
owhen the classes to instantiate are specified at run-
time, for example, by dynamic loading; or
oto avoid building a class hierarchy of factories that
parallels the class hierarchy of products; or
69
Applicability
●when instances of a class can have one of only a few
different combinations of state. It may be more
convenient to install a corresponding number of
prototypes and clone them rather than instantiating
the class manually, each time with the appropriate
state.
70
client
Operation()
p = prototype ->Clone()
Prototype
ConcretePrototype1
return copy of self
prototype
Clone()
return copy of self
Clone()
ConcretePrototype2
Clone()
PROTOTYPE
Structure
71
UNIT-III
Participants:
●Prototype (Graphic)
oDeclares an interface for cloning itself
●ConcretePrototype (Staff, WholeNote, HalfNote)
oImplements an interface for cloning itself
●Client (GraphicTool)
oCreates a new object by asking a prototype to clone itself
Collaborations:
●A client asks a prototype to clone Itself.
L5
72
Consequences
Adding and removing products at run-time.
Specifying new objects by varying values.
Specifying new objects by varying structure.
Reduced subclassing.
Configuring an application with classes dynamically.
73
Implementation
Using a prototype manager.
Implementing the Clone operation.
Initializing clones.
74
Known Uses
first example of the Prototype pattern was in Ivan Sutherland's
Sketchpad system
first widely known application of the pattern in an object oriented
language was in ThingLab, where users could form a composite
object and then promote it to a prototype by installing it in a
library of reusable objects
75
Related Patterns
Prototype and Abstract Factory are competing patterns in some
ways, as we discuss at the end of this chapter.
They can also be used together, however.
An Abstract Factory might store a set of prototypes from which to
clone and return product objects.
Designs that make heavy use of the Composite and Decorator
patterns often can benefit from Prototype as well.
76
77
79
80
abstract class ColorPrototype
{
public abstract ColorPrototype Clone();
}
------------------------------
class Color:ColorPrototype
{
public int Red;
public int Green;
public int Blue;
public override ColorPrototype Clone()
{
return this.MemberwiseClone() as ColorPrototype;
}
}81
private void button1_Click(object sender, EventArgs e)
{
Color c1 = new Color();
c1.Green = 255;
Color c2 = c1.Clone() as Color;
}
82
SINGELTON ● Intent:
oEnsure a class only has one instance, and provide a
global point of access to it.
●Motivation:
oSome classes should have exactly one instance
(one print spooler, one file system, one window manager)
oA global variable makes an object accessible but doesn’t
prohibit instantiation of multiple objects
oClass should be responsible for keeping track of its sole
interface
83
SINGELTON
●Usage:
●Often used for objects that need to provide global access
with the constraint of only one single instance in the
application
84
Applicability
●Use the Singleton pattern when
othere must be exactly one instance of a class, and it
must be accessible to clients from a well-known access
point.
owhen the sole instance should be extensible by
subclassing, and clients should be able to use an
extended instance without modifying their code.
85
Singleton
return uniquelnstancestatic Instance()
SingletonOperation()
GetSingletonData()
Static uniquelnstance
singletonData
SINGLETON
Structure
86
Participants and
Collaborations
●Singleton:
●Defines an instance operation that lets clients access its
unique interface
●Instance is a class operation (static in Java)
●May be responsible for creating its own unique instance
●Collaborations:
●Clients access a Singleton instance solely through
Singleton’s Instance operation.
87
Consequences
• Controlled access to sole instance.
• Reduced name space.
• Permits refinement of operations and representation.
• Permits a variable number of instances.
• More flexible than class
88
Implementation Points
●Generally, a single instance is held by the object, and
controlled by a single interface.
●Sub classing the Singleton may provide both default and
overridden functionality.
89
Known Uses
• A more subtle example is the relationship between classes
and their metaclasses.
• A metaclass is the class of a class, and each metaclass has
one instance.
• Metaclasses do not have names (except indirectly through
their sole instance), but they keep track of their sole
instance and will not normally create another.
90
Related pattern
• Many patterns can be implemented using the Singleton
pattern.
• See Abstract Factory, Builder , and Prototype.
91
Discussion of Creational Patterns
• There are two common ways to parameterize a system by
the classes of objects it creates:
• One way is to subclass the class that creates the objects
• The other way to parameterize a system relies more on
object composition
94
Discussion of Creational Patterns
• Which pattern is best depends on many factors.
• Abstract Factory doesn't offer much of an improvement,
because it requires an equally large Graphics Factory class
hierarchy.
• the Prototype pattern is probably the best for the drawing
editor framework, because it only requires implementing a
Clone operation on each Graphics class.
• Factory Method makes a design more customizable and
only a little more complicated.
97
Discussion of Creational Patterns
• Designs that use Abstract Factory, Prototype, or Builder
are even more flexible than those that use Factory Method,
but they're also more complex.
• Often, designs start out using Factory Method and evolve
toward the other creational patterns as the designer
discovers where more flexibility is needed.
98