Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Creational Patterns CS 236700: Software Design Winter 2004-2005/T8."— Presentation transcript:

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

2 2 Singleton: intent Ensure a class has one instance, and provide a global point of access to it

3 3 Singleton: structure Singleton static uniqueInstance data static instance() singletonOperation() getData() return uniqueInstance

4 4 Singleton: 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 5 Singleton: 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 6 Singleton: 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 7 Factory 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 8 Factory Method: motivation Document doc = createDocument(); docs.add(doc); doc.open(); Application createDocument() newDocument() openDocument() Document save() print() docs MyDocument MyApplication createDocument() creates return new MyDocument()

9 9 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 10 Factory 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 11 Factory Method: structure Product ConcreteProduct Creator factoryMethod() AnOperation() ConcreteCreator factoryMethod() creates... product= factoryMethod()... return new ConcreteProduct

12 12 Factory 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 13 Connecting parallel hierarchies LineFigure CreateManipulator() TextFigure CreateManipulator() LineManipulator DownClick() Drag() TextManipulator DownClick() Drag() Manipulator DownClick() Drag() Client Figure CreateManipulator() creates Localizes knowledge of which classes belongs together

14 14 Factory 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 15 Factory 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 16 Abstract Factory: intent Provide an interface for creating families of related or dependent objects, without specifying their concrete classes

17 17 Abstract Factory: motivation MotifWidgetFactory CreateScrollBar() CreateWindow() PMWidgetFactory CreateScrollBar() CreateWindow() PMWindowMotifWindow PMScrollBarMotifScrollBar WidgetFactory (abstract) CreateScrollBar() CreateWindow() Window ScrollBar Client creates

18 18 Abstract 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 19 Abstract 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 20 Abstract Factory: structure ConcreteFactory1 CreateProductA() CreateProductB() ConcreteFactory2 CreateProductA() CreateProductB() ProductA2 ProductA1 ProductB2 ProductB1 AbstractFactory CreateProductA() CreateProductB() AbstractProductA AbstractProductB Client creates

21 21 Abstract 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 22 Abstract 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 23 Prototype: intent Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype

24 24 Prototype: 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

25 25 Prototype: 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 26 Prototype: structure p = prototype->clone() Prototype clone() prototype Client operation() ConcretePrototype1 clone() ConcretePrototype clone() return copy of self

27 27 Prototype: 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 28 Prototype 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 29 Prototype: 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 30 Builder: intent Separate the construction of a complex object from its representation so that the same construction process can create different representations

31 31 Builder: 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 32 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 33 Builder: 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 34 Builder: structure

35 35 Builder: 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 36 Builder: 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 37 Builder: 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 38 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 39 Builder: 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 ConcreteBuilder s "No:" May introduce silent bugs


Download ppt "1 Creational Patterns CS 236700: Software Design Winter 2004-2005/T8."

Similar presentations


Ads by Google