1 / 39

Creational Patterns

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().

aggie
Télécharger la présentation

Creational Patterns

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

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

  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. 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. Singleton: implementation class Keyboard { private static Keyboard instance_ = new Keyboard(); public static Keyboard instance() { return instance_; } private Keyboard() { … } }

  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.

  8. 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

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

  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. 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

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

  17. Abstract Factory: motivation WidgetFactory (abstract) Client CreateScrollBar() CreateWindow() Window creates PMWindow MotifWindow MotifWidgetFactory PMWidgetFactory CreateScrollBar() CreateScrollBar() CreateWindow() CreateWindow() ScrollBar creates PMScrollBar MotifScrollBar creates creates

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

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

  24. 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

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

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

  31. 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) } }

  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. 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. Builder: structure

  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. 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. 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; };

  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_; }; 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: 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

More Related