1 creational patterns cs 236700: software design winter 2004-2005/t8

39
1 Creational Creational Patterns Patterns CS 236700: Software Design Winter 2004-2005/T8

Post on 21-Dec-2015

218 views

Category:

Documents


0 download

TRANSCRIPT

1

Creational PatternsCreational Patterns

CS 236700: Software Design

Winter 2004-2005/T8

2

Singleton: intentSingleton: intent

Ensure a class has one instance, and provide a global

point of access to it

Ensure a class has one instance, and provide a global

point of access to it

3

Singleton: structureSingleton: structure

Singleton

static uniqueInstancedata

static instance()singletonOperation()getData()

return uniqueInstance

4

Singleton: applicability + participantsSingleton: applicability + participants

Use the Singleton pattern when there must be exactly one instance of a class, and it must be

accessible to clients from a well-known access point when the sole instance should be extensible by subclassing,

and clients should be able to use an extended instance without modifying their code

Participants Singleton

defines an instance() operation that lets clients access its unique instance.

Instance is a class operation (i.e.: static)may be responsible for creating its own unique instance

5

Singleton: consequencesSingleton: consequences

Controlled access to a sole instance An elegant replacement for global variables More flexible than static member functions

Allows overriding The singleton may be extended to allow several instances

6

Singleton: implementationSingleton: implementation

class Keyboard{ private static Keyboard instance_ = new Keyboard();

public static Keyboard instance() { return instance_; }

private Keyboard() { … }}

class Keyboard{ private static Keyboard instance_ = new Keyboard();

public static Keyboard instance() { return instance_; }

private Keyboard() { … }}

7

Factory Method: intentFactory Method: intent

Define an interface for creating an object, but let subclasses decide which class to instantiate.

Lets a class defer instantiation to subclasses.

Define an interface for creating an object, but let subclasses decide which class to instantiate.

Lets a class defer instantiation to subclasses.

8

Factory Method: motivationFactory Method: motivation

Document doc = createDocument();docs.add(doc);doc.open();

Application

createDocument()newDocument()openDocument()

Document

save()print()

docs

MyDocumentMyApplication

createDocument()creates

return new MyDocument()

9

Factory Method: motivation (cont.)Factory Method: motivation (cont.)

Application class is responsible for creation (and management) of Documents

Problem: Application class knows: WHEN a new document should be

created Application class doesn’t know: WHAT KIND of document to

create

Solution: Application defines a virtual function, createDocument() MyApplication makes sure that createDocument() will

create a product (Document) of the correct type.

10

Factory Method: participantsFactory Method: participants

Product (Document) defines the interface of objects the factory method creates

ConcreteProduct (MyDocument) implements the Product interface

Creator (Application) declares the factory method, which returns an object of type

Product. May also define a default implementation of the factory

method that returns a default ConcreteProduct object.

ConcreteCreator (MyApplication) overrides the factory method to return an instance of a

ConcreteProduct

11

Factory Method: structureFactory Method: structure

Product

ConcreteProduct

Creator

factoryMethod()AnOperation()

ConcreteCreator

factoryMethod()creates

...product= factoryMethod()...

return new ConcreteProduct

12

Factory Method: consequencesFactory Method: consequences Advantage

Concrete (Dynamic) types are isolated from the client code => Reduced level of Deja-vu.

Provides hooks for subclasses A standard technique for subclasses to affect their parents'

behavior

Connects parallel class hierarchies see next slide for example

Potential disadvantage clients might have to subclass the Creator class just to

create a particular (i.e., 1) ConcreteProduct object

13

Connecting parallel hierarchiesConnecting parallel hierarchies

LineFigure

CreateManipulator()TextFigure

CreateManipulator()

LineManipulator

DownClick()Drag()

TextManipulator

DownClick()Drag()

Manipulator

DownClick()Drag()

ClientFigure

CreateManipulator()

creates

creates

Localizes knowledge of which classes belongs together

14

Factory Method: applicabilityFactory Method: applicability

Use the Factory Method pattern when a class can’t anticipate the class of objects it must create a class wants its subclasses to specify the object it creates classes delegate responsibility to one of several helper

subclasses, and you want to localize the knowledge of which helper subclass is the delegate

15

Factory Method: implementationFactory Method: implementation

Two major varieties Creator declares ABSTRACT factory method,

ConcreteCreator implements it Creator defines a default implementation for factory method

Parameterized factory methods lets the factory method to create multiple kinds of objects factory methods takes a parameter: a kind of object to create all products have to share a Product interface

16

Abstract Factory: intentAbstract Factory: intent

Provide an interface for creating families of related or dependent objects, without specifying their concrete classes

Provide an interface for creating families of related or dependent objects, without specifying their concrete classes

17

Abstract Factory: motivationAbstract Factory: motivation

MotifWidgetFactory

CreateScrollBar()CreateWindow()

PMWidgetFactory

CreateScrollBar()CreateWindow()

PMWindow MotifWindow

PMScrollBar MotifScrollBar

WidgetFactory (abstract)

CreateScrollBar()CreateWindow() Window

ScrollBar

Client

creates

creates

creates

creates

18

Abstract Factory: applicabilityAbstract Factory: applicability

Use the Abstract Factory pattern when A system should be independent of how its products are

created Products are grouped into families A family is intended to be used together, and you need to

enforce this constraint You want to provide a class library of products, and you want

to reveal just their interfaces, not their implementations

19

Abstract Factory: participantsAbstract Factory: participants

AbstractFactory (WidgetFactory) declares an interface for operations that create abstract

product objects

ConcreteFactory (MotifWidgetFactory,…) implements the operations to create concrete product objects

AbstractProduct (Window, ScrollBar) declared an interface for a type of product object

ConcreteProduct (MotifWindow, MotifScrollBar) defines a product object to be created by the corresponding

concrete factory implements the AbstractProduct interface

Client uses only interfaces declared by AbstractFactory and

AbstractProduct classes

20

Abstract Factory: structureAbstract Factory: structure

ConcreteFactory1

CreateProductA()CreateProductB()

ConcreteFactory2

CreateProductA()CreateProductB()

ProductA2 ProductA1

ProductB2 ProductB1

AbstractFactory

CreateProductA()CreateProductB()

AbstractProductA

AbstractProductB

Client

creates

creates

creates

creates

21

Abstract Factory: consequencesAbstract Factory: consequences

Concrete (Dynamic) types are isolated from the client code

Exchanging a product family is easy Reduced risk of mixing of families Supporting new kinds of products is difficult

AbstractFactory interface fixes the set of products that can be created

involves changing AbstractFactory and all its subclasses interfaces

22

Abstract Factory: implementationAbstract Factory: implementation

Factories as singletons Creating the products

use Factory Method pattern declare FactoryMethod for each kind of product in AbstractFactory

override FactoryMethod in ConcreteFactory use Prototype pattern for ConcreteFactory if many product

families are possible initialize the concrete factory with a prototypical instance of each

product in the family concrete factory will create a new product by cloning the

prototype no need for a new concrete factory class for each new family

Defining extensible factories Via parameterization -- I.e., object = factory.make ( typeA ) ; Via mixing concrete and abstract factory hierarchies.

23

Prototype: intentPrototype: intent

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype

24

Prototype: motivationPrototype: motivation

Tool

manipulate()

RotateTool

manipulate()

p = prototype.clone()while (user drags mouse) {

p.draw(mouse_position)}insert p into drawing

prototype

GraphicTool

manipulate()

Graphic

draw(position)clone()

EditBox

draw(position)clone()

Slider

draw(position)clone()

return copy of self return copy of self

25

Prototype: participantsPrototype: participants

Prototype (Graphic) declared an interface for cloning itself

ConcretePrototype (EditBox, Slider) implements an operation for cloning itself

Client (GraphicTool) creates a new object by asking a prototype to clone itself

26

Prototype: structurePrototype: structure

p = prototype->clone()

Prototype

clone()prototypeClient

operation()

ConcretePrototype1

clone()

ConcretePrototype

clone()

return copy of self return copy of self

27

Prototype: applicabilityPrototype: applicability

Use the Prototype pattern when a system should be independent of how its products are

created; and when the classes to instantiate are specified at run-time; or to avoid building a hierarchy of factories; or State of the created instance cannot be easily specified

28

Prototype pattern - consequencesPrototype pattern - consequences Adding and removing prototypes at run-time Specifying new objects by varying values

By adding a new prototype you actually define a new 'type' which your program can instantiate

Reduced subclassing (See previous slide)

Pseudo Dynamic loading

29

Prototype: implementationPrototype: implementation

Simple prototyping: Client code must provide an existing prototype object

Using a prototype manager: The manager keeps a dictionary of available prototypes Client code can add/remove prototypes to/from the dictionary Instantiation:

client code specifies a "key" value. The Manager duplicates the prototype matching this key

Implementing the clone() operation “shallow copy versus deep copy”

30

Builder: intentBuilder: intent

Separate the construction of a complex object from its

representation so that the same construction process can create

different representations

Separate the construction of a complex object from its

representation so that the same construction process can create

different representations

31

Builder: MotivationBuilder: Motivation

DocConverter

buildResult()

IMaker

addLine(line)addImage(img)

HtmlMaker

addLine(line)addImage(img)getResult()

PdfMaker

addLine(line)addImage(img)getResult()

while(parts.hasMore()) { t = parts.next(); switch(t.type) { case LINE: builder.addLine(t.line) case IMAGE: builder.addImage(t.img) }}

32

Builder: motivation (cont.)Builder: motivation (cont.)

DocConverter is expected to convert a document to many output formats (html, pdf, etc…)

Number of possible conversions is open-ended. The solution:

Client code "loads" the appropriate maker object Whenever the DocConverter recognizes a complete

element (either a line or an image), it issues a corresponding request to the IMaker object.

At the end, client code issues a getResult() request on the active maker

33

Builder: participantsBuilder: participants

Builder (IMaker) Specifies an interface for creating/assembling parts of a

product.

ConcreteBuilder (HtmlMaker, PdfMaker) Implements the Builder interface

Director (DocConverter) Constructs an object of an unknown type using the Builder

interface

Product (HtmlDocument, PdfDocument) Complete object returned by invoking getResult() on the

ConcreteBuilder

34

Builder: structureBuilder: structure

35

Builder: consequencesBuilder: consequences

Isolates code for construction and representation Construction logic is encapsulated within the director Product structure is encapsulated within the concrete builder => Lets you vary a product's internal representation

Supports fine control over the construction process Breaks the process into small steps

36

Builder: applicabilityBuilder: applicability

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're assembled.

The construction process must allow different representations for the object that's constructed

37

Builder: implementationBuilder: implementation

public interface IBuilder { void begin_node(); void end_node(); void add_data(String s);};

public Class TextBuilder impelements IBuilder { public void begin_node() { depth_ += 2; } public void end_node() { depth_ -= 2; } public void add_data(String s) { for(int i = 0; i < depth_; ++i) result_ += ‘ ‘; result_ += s + '\n‘; }

public String result_ = ““; int depth_ = 0;};

public interface IBuilder { void begin_node(); void end_node(); void add_data(String s);};

public Class TextBuilder impelements IBuilder { public void begin_node() { depth_ += 2; } public void end_node() { depth_ -= 2; } public void add_data(String s) { for(int i = 0; i < depth_; ++i) result_ += ‘ ‘; result_ += s + '\n‘; }

public String result_ = ““; int depth_ = 0;};

38

Builder: implementation Builder: implementation

public class Director { void set_builder(IBuilder b) { b_ = b; } void process(Node r) { if(r == null) return; b_.begin_node(); b_.add_data(r.val_); process(r.first_); b_.end_node();

process(r.next_); } IBuilder b_;};

public class Director { void set_builder(IBuilder b) { b_ = b; } void process(Node r) { if(r == null) return; b_.begin_node(); b_.add_data(r.val_); process(r.first_); b_.end_node();

process(r.next_); } IBuilder b_;};

static void main() { Node root; Director dir; TextBuilder tb; … dir.set_builder(tb); dir.process(root);

String s = tb.result_; System.out.print(s);}

static void main() { Node root; Director dir; TextBuilder tb; … dir.set_builder(tb); dir.process(root);

String s = tb.result_; System.out.print(s);}

39

Builder: implementationBuilder: implementation

The Builder interface (IMaker) Must be general enough to allow construction of many

products

Abstract base class for all products? Usually not feasible (products are highly different)

Default implementation for methods of Builder? "Yes": May decrease amount of code in ConcreteBuilders "No:" May introduce silent bugs