1 / 64

OOMPA Lecture 10

Learn about design patterns including Singleton, Factory Method, and Abstract Factory. Explore their purpose, implementation, and use cases in software development.

emaddox
Download Presentation

OOMPA Lecture 10

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. OOMPA Lecture 10 • Design Patterns • Singleton • Factory Method • Abstract Factory • Mediator

  2. Structural Patterns • Structural Patterns • Adapter, Façade, Composite • Concerned with the composition of classes or objects • Structural class patterns use inheritance to compose interfaces or implementations. • Structural object patterns describe ways to compose objects to realize new functionality.

  3. Behavioral Patterns • Behavioral Patterns • Command, Observer, Mediator, Strategy • Characterize the ways in which classes or objects interact and distribute responsibility • Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects. • Behavioral patterns also describe patterns of communication between objects and classes.

  4. Creational Patterns • Creational Patterns • Abstract Factory, Factory Method, Singleton • Concerned with object creation • Who creates what, when and how

  5. Singleton Pattern • The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. • Examples: • There can be many printers in a system but there should only be one printer spooler. • There should be only one instance of a WindowManager. • There should be only one instance of a filesystem.

  6. Singleton Pattern • How do we ensure that a class has only one instance and that the instance is easily accessible? • A global variable makes an object accessible, but does not keep you from instantiating multiple objects. • A better solution is to make the class itself responsible for keeping track of its sole instance. The class ensures that no other instance can be created (by intercepting requests to create new objects) and it provides a way to access the instance.

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

  8. Singleton Class Diagram

  9. Singleton Particpants • Singleton • Defines an Instance operation that lets clients access its unique instance. Instance is a class operation (static method) • May be responsible for creating its own unique instance • Client • Accesses a Singleton instance solely through the Singleton’s Instance() method.

  10. Singleton Consequences • Controlled access to sole instance Because the Singleton class encapsulates its sole instance, it can have strict control over how and when clients access it. • Reduced name space The Singleton pattern is an improvement over global variables. It avoids polluting the name space with global variables that store sole instances.

  11. Singleton Consequences • Permits refinement of operations and representations The Singleton class may be subclassed and it is easy to configure an application with an instance of this extended class at run-time. • More flexible than class operations An alternative is to use static member functions. However it is difficult to change the design to allow more than one instance of a class and static member functions are not polymorphic, so subclasses can not override them.

  12. Singleton Implementation • Ensuring a unique instance The Singleton pattern makes the sole instance a normal instance of a class, but that class is written so that only one instance can ever be created. A common way to do this is to hide the operation that creates the instance behind a static class operation that guarantees that only one instance is created.

  13. Singleton Sample Code class Singleton { private static Singleton instance; static Singleton Instance() {if (instance == null) // if not created yet instance = new Singleton(); // create once return instance; } // clients access the Singleton exclusively through // the Instance() member function protected Singleton() {} // the constructor is protected, such that a client // can never instantiate a Singleton }

  14. Singleton Sample Code class Singleton { private static Singleton instance; static Singleton Instance(SingletonType t) { if (instance == null) { if (t==SINGLETON) instance = new Singleton(); if (t==MYSINGLETON) instance = new MySingleton(); } return instance; } protected Singleton() {} } class MySingleton extends Singleton { … }

  15. Factory Method • Factory Method defines an interface for creating an object, but let subclasses decide which class to instantiate. • Factory Method lets a class defer instantiation to subclasses. • Frameworks use abstract classes to define and maintain relationships between objects. • A Framework is often responsible for creating these objects as well.

  16. Factory Method • Consider a framework for applications that can present multiple documents to the user. • The framework contains abstractions for Application and Document. • Both classes are abstract and clients have to subclass them to realize their application-specific implementations. • To create a drawing application for example, we define sub-classes DrawingApplication and DrawingDocument.

  17. Factory Method • The particular Document sub-class is application specific, the Application class can not predict the sub-class of a Document to instantiate. • The Application only knows when a new document should be created, not what kind of Document to create. • The problem, the framework must instantiate classes, but it only knows about abstract classes, which it cannot instantiate. • The Factory Method encapsulates the knowledge of which Document sub-class to create and moves this knowledge out of the framework.

  18. Factory Method Class Diagram

  19. Factory Method Applicability Use the Factory Method pattern when • A class cannot anticipate the class of objects it must create. • A class wants its sub-classes to specify the objects it creates. • Classes delegate responsibility to one of several helper sub-classes, and you want to localize the knowledge of which helper sub-class is the delegate.

  20. Factory Method Class Diagram

  21. Factory Method Participants • Product • Defines the interface of objects the factory method creates • ConcreteProduct • Implements the Product interface

  22. Factory Method Participants • Creator • Declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct • May call the factory method to create a Product object • ConcreteCreator • Overrides the factory method to return an instance of a ConcreteProduct

  23. Factory Method Consequences • Factory eleminates the need to bind application-specific classes into your code. The code only deals with the Product interface, therefore it can work with any user-defined Concrete-Product classes. • A potential disadvantage is that clients might have to sub-class the Creator class just to create a particular ConcreteProduct object.

  24. Factory Method Consequences • Provides hooks for subclasses: Creating objects inside a class with a factory method is always more flexible than creating an object directly. Factory methods give sub-classes a hook for providing an extended version of an object. • Connects parallel class hierarchies:

  25. Factory Method Implementation • Two main variations of Factory Method • Creator is an abstract class and does not provide an implementation for factory method. Requires sub-classes to define an implementation, but you do not have to instantiate unforeseeable classes. • Creator is a concrete class and provides a default implementation for factory method. The Creator uses the factory method primarily for flexibility, allowing sub-classes to change the class of objects their parent class instantiates if necessary.

  26. Factory Method Implementation • Parameterized factory methods • The factory method can create multiple kinds of products. The factory method takes a parameter that identifies the kind of object to create. All objects the factory method creates share the Product interface. class Creator { Product FactoryMethod(ProductID id) { if (id==MINE) return new MyProduct(); if(id==YOURS) return new YourProduct(); } }

  27. Factory Method Implementation • Using templates to avoid subclassing: In C++ one can use a template sub-class of Creator that is parameterized by the Product class. template <class TheProduct > class Creator { public: virtual Product* CreateProduct() { return new TheProduct; }; }; Class MyProduct : public Product { … }; Creator<MyProduct> my Creator;

  28. Abstract Factory • Abstract factory provides an interface for creating families of related or dependent objects without specifying their concrete classes.

  29. Abstract Factory • Consider a user-interface toolkit that supports multiple look-and-feel standards such as Motif and Presentation Manager. • Different toolkits define different appearances and behaviors for user interface widgets like scroll-bars, windows and buttons. • To be portable across different toolkits an application should not hard-code its widgets for a particular toolkit.

  30. Abstract Factory • Abstract Factory solves this problem by defining an abstract WidgetFactory class that declares an interface for creating each basic kind of widget. • There is also an abstract class for each kind of widget, and concrete sub-classes implement widgets for specific toolkits. • Widget Factory (Factory Method) provides an interface that returns a new widget object for each abstract widget class. • Clients use Widget Factory to obtain widget instances but are unaware of the concrete classes they are using.

  31. Abstract Factory Use the abstract factory pattern when • A system should be independent of how its products are created, composed and represented. • A system should be configured with multiple families of products. • A family of related product objects is designed 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.

  32. Abstract Factory Class Diagram

  33. Abstract Factory Participants • AbstractFactory (WidgetFactory) • Declares an interface for operations that create abstract product objects. • ConcreteFactory (MotifWidgetFactory, PMWidgetFactory) • Implements the operations to create concrete products.

  34. Abstract Factory Participants • AbstractProduct (Window, ScrollBar) • Declares an interface for a type of product. • ConcreteProduct (MotifWindow, MotifScrollBar) • Defines a product object to be created by the corresponding concrete factory. • Implements the AbstractProduct interface • Client • Uses only the interfaces declared by AbstractFactory and AbstractProduct

  35. Abstract Factory Collaborations • Normally a single instance of a ConcreteFactory class is created at run-time. ConcreteFactory is implemented as a Singleton. • AbstractFactory defers the creation of product objects to its ConcreteFactory sub-class, using the Factory Method pattern.

  36. Abstract Factory Consequences • Abstract Factory isolates classes: It helps you to control the classes of objects that an application creates. It isolates clients from implementation classes as the client manipulates instances solely through their abstract interfaces. • It makes exchanging product families easy: The class of a concrete factory appears only once in an application – that is where it is instantiated. This makes it easy to change the concrete factory an application uses. It can use different product configurations simply by changing the ConcreteFactory.

  37. Abstract Factory Consequences • It promotes consistency among products: When product objects in a family are designed to work together, it is important that the application use objects from only one family at a time. • Supporting new kinds of products is difficult: Extending abstract factories to produce new kinds of Products is difficult, because the AbstractFactory interface fixes the set of products that can be created. Supporting new products requires extending the factory interface, which involves changing the AbstractFactory class and all its ConcreteFactory sub-classes.

  38. Abstract Factory Implementation • Factories as Singletons: An application typically needs only one instance of a ConcreteFactory per product family. • Creating the Products: AbstractFactory only declares an interface for creating products. It is up to the ConcreteProduct sub-classes to actually create them. The most common way to do this is do define a Factory Method for each Product. • AbstractFactory vs. FactoryMethod • AbstractFactory  Creator • ConcreteFactory  ConcreteCreator • AbstractProduct  Product • Product  ConcreteProduct

  39. Mediator Pattern • Different dialog boxes will have different dependencies between widgets, which makes it impossible to simply reuse a standard set of widget classes. • Instead widget classes have to be customized to reflect dialog-specific dependencies, which would require a large number of separate subclasses for different types of dialogs.

  40. Coupling between Classes Special ListBox button field list list Special Button Special Entry Field button field

  41. Mediator Pattern • Encapsulating the collective behavior in a separate Mediator object avoids these problems. • A Mediator object is responsible for controlling and coordinating the interactions of a group of objects. • The Mediator serves as an intermediary that keeps objects in the group from refering to each other explicitly. • The objects only know the Mediator thereby reducing the number of interactions.

  42. Mediator Pattern director ListBox Client director FormDialog Director list button field Button Entry Field director director

  43. Mediator Pattern • The FormDialogDirector is the mediator between the widgets in the dialog box. • The FormDialogDirector knows the widgets in a dialog and coordinates their interaction. • The FormDialogDirector acts as a hub of communications for widgets.

  44. Mediator Sequence Diagram aFormDialog Director anEntry Field aButton aClient aListBox ShowDialog() Widget Changed() Get Selection() SetText() EnableButton()

  45. Mediator Structure director • DialogDirector • ShowDialog() • CreateWidgets() • WidgetChanged(w) • Widget • Changed() Director-> WidgetChanged(this) • ListBox • GetSelection() list • FormDialogDirector • CreateWidgets() • WidgetChanged(w) • EntryField • SetText() field

  46. Mediator Pattern • DialogDirector is an abstract class that defines the overall behavior of a dialog. • Clients call the ShowDialog operation to display the dialog on the screen. • CreateWidgets is an abstract operation for creating the widgets of a dialog. • WidgetChanged is another abstract operation, widgets call it to inform their director that they have changed. • DialogDirector subclasses override CreateWidgets to create the proper widgets, and they override WidgetChanged to handle the changes.

  47. Mediator Sample Code class DialogDirector { public: virtual void ShowDialog(); virtual void WidgetChanged(Widget *)=0; protected: DialogDirector(); virtual void CreateWidgets() = 0; };

  48. Mediator Sample Code class Widget { public: Widget(DialogDirector*); virtual void Changed(); virtual void HandleMouseEvent(MouseEvent& event); private: DialogDirector* director_; }; void Widget::Changed() { director->WidgetChanged(this); }

  49. Mediator Sample Code class ListBox : public Widget { public: ListBox(DialogDirector*); virtual const string GetSelection(); virtual void HighLight(string selection); virtual void SetList(list<string> newlistItems); virtual void HandleMouseEvent(MouseEvent& event); private: list<string> listItems; };

  50. Mediator Sample Code class EntryField : public Widget { public: EntryField(DialogDirector*); virtual const string GetText(); virtual void SetText(const string newtext); virtual void HandleMouseEvent(MouseEvent& event); private: string text; };

More Related