420 likes | 613 Views
Creational Patterns. CS 236700: Software Design Winter 2004-2005/T8. Singleton: intent. Ensure a class has one instance, and provide a global point of access to it. Singleton: structure. Singleton. static uniqueInstance. data. static instance(). singletonOperation().
E N D
Creational Patterns CS 236700: Software Design Winter 2004-2005/T8
Singleton: intent Ensure a class has one instance, and provide a global point of access to it
Singleton: structure Singleton static uniqueInstance data static instance() singletonOperation() return uniqueInstance getData()
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
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
Singleton: implementation class Keyboard { private static Keyboard instance_ = new Keyboard(); public static Keyboard instance() { return instance_; } private Keyboard() { … } }
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.
Factory Method: motivation Document Application docs createDocument() save() Document doc = createDocument(); newDocument() docs.add(doc); print() openDocument() doc.open(); MyApplication MyDocument return new MyDocument() createDocument() creates
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.
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
Factory Method: structure Creator ... product= factoryMethod() factoryMethod() Product ... AnOperation() ConcreteCreator ConcreteProduct return new ConcreteProduct factoryMethod() creates
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
Connecting parallel hierarchies Manipulator Figure Client DownClick() CreateManipulator() Drag() LineManipulator TextManipulator LineFigure TextFigure DownClick() DownClick() CreateManipulator() CreateManipulator() Drag() Drag() creates creates Localizes knowledge of which classes belongs together
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
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
Abstract Factory: intent Provide an interface for creating families of related or dependent objects, without specifying their concrete classes
Abstract Factory: motivation WidgetFactory (abstract) Client CreateScrollBar() CreateWindow() Window creates PMWindow MotifWindow MotifWidgetFactory PMWidgetFactory CreateScrollBar() CreateScrollBar() CreateWindow() CreateWindow() ScrollBar creates PMScrollBar MotifScrollBar creates creates
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
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
Abstract Factory: structure AbstractFactory Client CreateProductA() CreateProductB() AbstractProductA creates ProductA1 ProductA2 ConcreteFactory1 ConcreteFactory2 CreateProductA() CreateProductA() CreateProductB() CreateProductB() AbstractProductB creates ProductB1 ProductB2 creates creates
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
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.
Prototype: intent Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype
Prototype: motivation Graphic Tool draw(position) manipulate() clone() prototype RotateTool GraphicTool Slider EditBox manipulate() manipulate() draw(position) draw(position) clone() clone() p = prototype.clone() while (user drags mouse) { p.draw(mouse_position) return copy of self return copy of self } insert p into drawing
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
Prototype: structure Client Prototype prototype operation() clone() p = prototype->clone() ConcretePrototype1 ConcretePrototype clone() clone() return copy of self return copy of self
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
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
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”
Builder: intent Separate the construction of a complex object from its representation so that the same construction process can create different representations
DocConverter IMaker HtmlMaker PdfMaker buildResult() addLine(line) addImage(img) addLine(line) addImage(img) getResult() addLine(line) addImage(img) getResult() Builder: Motivation while(parts.hasMore()) { t = parts.next(); switch(t.type) { case LINE: builder.addLine(t.line) case IMAGE: builder.addImage(t.img) } }
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
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
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
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
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; };
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_; }; static void main() { Node root; Director dir; TextBuilder tb; … dir.set_builder(tb); dir.process(root); String s = tb.result_; System.out.print(s); }
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 ConcreteBuilders • "No:" May introduce silent bugs