Presentation is loading. Please wait.

Presentation is loading. Please wait.

OOMPA Lecture 10 Design Patterns Singleton Factory Method

Similar presentations


Presentation on theme: "OOMPA Lecture 10 Design Patterns Singleton Factory Method"— 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 Structure Singleton static Instance() SingletonOperation()
GetSingletonData() static uniqueinstance singletonData return uniqueinstance

9 Singleton Class Diagram

10 Singleton Particpants
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.

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

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

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

14 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

15 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 { … }

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

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

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

19 Factory Method Class Diagram

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

21 Factory Method Class Diagram

22 Factory Method Participants
Product Defines the interface of objects the factory method creates ConcreteProduct Implements the Product interface

23 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

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

25 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:

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

27 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(); }

28 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;

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

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

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

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

33 Abstract Factory Class Diagram

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

35 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

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

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

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

39 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

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

41 Coupling between Classes
Special ListBox button field list list Special Button Special Entry Field button field

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

43 Mediator Pattern ListBox Client FormDialog Director Button Entry Field

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

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

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

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

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

49 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); }

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

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

52 Mediator Sample Code class Button : public Widget { public:
Button(DialogDirector*); virtual void SetText(const string newtext); virtual void HandleMouseEvent(MouseEvent& event); virtual void Activate(); virtual void DeActivate(); private: bool active; };

53 Mediator Sample Code class FormDialogDirector : public DialogDirector
{ public: FormDialogDirector() virtual void WidgetChanged(Widget *); protected: virtual void CreateWidgets(); private: ListBox* list; EntryField* field; Button* ok_button; Button* cancel_button; };

54 Mediator Sample Code void FormDialogDirector::CreateWidgets() {
list = new ListBox(this); field = new EntryField(this); ok_button = new Button(this); cancel_button = new Button(this); ok_button->DeActivate(); ok_button->SetText(”OK”); cancel_button->Activate(); cancel_button->SetText(”Cancel”); // fill the ListBox with the available names list->SetList(...); }

55 Mediator Sample Code void FormDialogDirector::WidgetChanged
(Widget* ChangedWidget) { if (ChangedWidget==list) field->SetText(list->GetSelection()); if (ChangedWidget==field) { list->Highlight(field->GetText()); if (field->GetText() != ””) ok_button->Activate(); else ok_button->DeActivate(); } } if (ChangedWidget==ok_button) ...

56 Mediator Applicability
Use the Mediator pattern when A set of objects communicate in well-defined complex ways. The resulting interdependencies are unstructured and difficult to understand. Reusing an object is difficult because it refers to and communicates with many other objects. A behavior that is distributed between several classes should be customizable without a lot of subclassing.

57 Mediator Pattern Structure
Colleague Concrete Mediator Concrete ColleagueA Concrete ColleagueB

58 Mediator Pattern Participants
defines an interface for communicating with Colleague objects. ConcreteMediator Implements cooperative behavior by coordinating Colleague objects. Colleague classes Each colleague knows its mediator Each colleague communicates with its Mediator whenever it would have otherwise communicated with another colleague

59 Mediator Pattern Collaborations
Colleagues send and receive requests from a Mediator object. The Mediator implements the cooperative behavior by routing requests between the appropriate colleagues

60 Mediator Pattern Consequences
The Mediator pattern limits subclassing. A mediator localizes behavior that otherwise would be distributed among several objects. Changing this behavior requires subclassing Mediator only, Colleague classes can be reused. The Mediator pattern decouples colleagues. A mediator promotes loose coupling between colleagues. You can vary and reuse Colleague and Mediator classes independently.

61 Mediator Pattern Consequences
The Mediator pattern simplifies object protocols. A mediator replaces many-to-many interactions with one-to-many interactions between the mediator and its colleagues. One-to-many relationships are easier to understand, maintain and extend. The Mediator pattern abstracts how objects cooperate. Making mediation an independent concept and encapsulating it in an object lets you focus on how objects interact apart from their individual behavior. That can help clarify how objects interact in a system.

62 Mediator Pattern Consequences
The mediator pattern centralizes control. The Mediator pattern trades complexity of interaction for complexity in the mediator. Because a mediator encapsulates protocols, it can become more complex than an individual colleague. This can make the mediator itself a monolith that is hard to maintain.

63 Mediator Pattern Implement.
Omitting the abstract Mediator class. There is no need to define an abstract Mediator class when colleagues work with only one mediator. The abstract coupling that the Mediator class provides lets colleagues work with different subclasses and vice versa.

64 Mediator Pattern Implement.
Colleague-Mediator communication. Colleagues have to communicate with their mediator when an event of interest occurs. One approach is to implement the Mediator as an Observer. Colleague classes act as Subjects, sending notifications to the mediator whenever they change state. The mediator responds by propagating the effects of the change to the other colleagues.

65 Mediator Pattern Game Dice Player Game Manager Token Board manager


Download ppt "OOMPA Lecture 10 Design Patterns Singleton Factory Method"

Similar presentations


Ads by Google