Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 DesignPattern-3 Creational Patterns Suntae Kim Kangwon National University

Similar presentations


Presentation on theme: "1 DesignPattern-3 Creational Patterns Suntae Kim Kangwon National University"— Presentation transcript:

1 1 DesignPattern-3 Creational Patterns Suntae Kim Kangwon National University stkim@kangwon.ac.kr

2 2 This Chapter in our course Introduction To Design Patterns Structural Patterns Behavioral Patterns Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 1 OO Concepts and Design Principle Creational Patterns

3  Creational patterns  Increase Flexibility By abstracting the object creation step.  Decrease coupling by separating the real objects and its creation part.  are the following patterns  Abstract Factory  Builder  Factory Method  Prototype  Singleton 3

4 Example  Example: Building a maze for a computer game  Simple find the solution path in the maze.  A maze is composed of rooms, walls and doors.  A rom is connected to walls and doors in the four directions.  There is only one door between rooms.  The maze is compose of many rooms.  Class diagram?  Classes: Maze, Room, Wall, Door,  Abstract Room, Wall, Door with the MapSite object, because they are common elements in the maze. 4

5 Example -2  MapSite’s Method : Enter()  Changes the location of a Player  Change the location of the player if the MapSite is the Room object  Change the location of the player if the MapSite is the opened Door object. If not the move is not permitted. Need to define an attribute to maintain a data for open/closed door.  Room’s Method: SetSide(), GetSide()  Methods for storing the Wall or Door object surrounding the Room object.  Maze’s Method: AddRoom()  A method for adding a new Room object. 5

6 Example -3  A class diagram for Maze 6

7 Example -4 class MapSite { public: virtual void Enter() = 0; }; class Room : public MapSite { public: Room(int = 0); Room(const Room&); virtual Room* Clone() const; void InitializeRoomNo(int); MapSite* GetSide(Direction); void SetSide(Direction, MapSite*); virtual void Enter(); private: MapSite* _sides[4]; int _roomNumber; }; class Wall : public MapSite { public: Wall(); Wall(const Wall&); virtual Wall* Clone() const; virtual void Enter(); }; class Door : public MapSite { public: Door(Room* = 0, Room* = 0); Door(const Room&); virtual Door* Clone() const; void Initialize(Room*, Room*); virtual void Enter(); Room* OtherSideFrom(Room*); private: Room* _room1; Room* _room2; bool _isOpen; }; class Maze { public: Maze(); Maze(const Maze&); Room* RoomNo(int); void AddRoom(Room*); virtual Maze* Clone() const; private: //... }; 7

8 Example -5  MazeGame::CreateMaze()  Create Maze (aMaze).  Create two Room objects (r1, r2).  Create the one Door object (theDoor).  Add r1 and r2 to aMaze.  r1 is located at the eastern side of the room, walls are positioned in other sides.  r2 is located at the western side of the room, walls are positioned in other sides. Maze* MazeGame::CreateMaze() { Maze* aMaze = new Maze; Room* r1 = new Room(1); Room* r2 = new Room(2); Door *theDoor = new Door(r1, r2); aMaze->AddRoom(r1); aMaze->AddRoom(r2); r1->SetSide(North, new Wall); r1->SetSide(East, theDoor); r1->SetSide(South, new Wall); r1->SetSide(West, new Wall); r2->SetSide(North, new Wall); r2->SetSide(East, new Wall); r2->SetSide(South, new Wall); r2->SetSide(West, theDoor); return aMaze; } 8 r1r2door wall

9 Example -6  Problems:  The code (MazeGame::CreateMaze()) should be changed whenever a new structure of the maze should be created, because it is hard corded.  What if the following elements should be newly added for creating a magic maze? DoorNeedingSpell EnchantedRoom  Check which code should be updated?  Is it easy or hard? It is hard to update because the creation of the objects are hard coded.  We can solve these problems using Creational Patterns 9

10 Factory Method: Motivation The elements are already defined as Application, Document and View, and their interactions are also defined. - Main elements : Application, Document, View - Interactions among Application, Document, and View are also defined. The elements are already defined as Application, Document and View, and their interactions are also defined. - Main elements : Application, Document, View - Interactions among Application, Document, and View are also defined. Application DocumentView 10

11 DrawingApplication DrawingDocumentDrawingView [Drawing application] ViewerApplication ViewerDocumentViewerView [Viewer application] ???Application ???Document???View [??? application] Factory Method: Motivation -2 What if these kinds of the systems should be repeatedly provided? The structure and Interactions among Application, Document and View should be implemented all the time. 11

12 Factory Method: Motivation -3  Solution 1:  Interactions among Application, Document and View are implemented in advance. The application specific parts are implemented by inheriting them. Application DocumentView DrawingDocumentDrawingView DrawingApplication Implement in advance 12

13 Factory Method: Motivation -4  Problems in the Solution #1 Application DocumentView DrawingDocument DrawingApplication How can we create the DrawingDocument object in the Application object? Application::NewDocument() { Document *doc = new Document; … } 13

14 Factory Method: Motivation -5  How to create the DrawingDocument object in the Application Object Subclassing the CreateDocument method for creating a real object. Subclassing the CreateDocument method for creating a real object. Application DocumentView DrawingDocument DrawingApplication Application::NewDocument() { Document *doc = CreateDocument(); … } // override application::CreateDocument DrawingApplication::CreateDocument() { return new DrawingDocument; } > 14

15 Factory Method: Motivation -6 15

16 Factory Method Spec.  Intent  Define the interface method for creating an object, and delegate it into the subclasses.  Also Known As  Virtual Constructor  Motivation  Previous Slides  Applicability use this pattern when  The concrete classes are not defined yet.  The object creation should be delegated into the subclasses. 16

17 Factory Method Spec. -2  Structure 17

18 Factory Method Spec. -3  Participants  Product (Document, View) factoryMethod() defines an interface for object creation.  ConcreteProduct (DrawingDocument, DrawingView) Realization class for the Product Interface  Creator (Application) Defines the factoryMethod() method for object creation. Use the factoryMethod() method when objects are needed.  ConcreteCreator (DrawingApplication) Implement the factoryMethod() method for creating the Product object.  Collaborations  Call the factoryMethod() method when the Creator object want to create the Product object, not calling the ConcreteProduct object.  The real factorymethod() method is called in the ConcreteCreator class inheriting the Creator class. 18

19 Factory Method Spec. -4  Consequences  Provides hooks for subclasses Increase the flexibility using the factoryMethod() method in the class. New Product class can be launched in the released program by just overring the factoryMethod() method in the subclass.  Connects parallel class hierarchies In the previous example, the relationship between the Creator and Product is 1:1. By enhancing it, the m:m relationships are also realized. Refer to the next slide. 19

20 Factory Method Spec. -5  Example: parallel class hierarchies Creators Products createManipulator(): the factoryMethod() method for creating the Product objects. 20

21 Factory Method Spec. -6  Implementation  Two major varieties if Creator is an abstract class  the factoryMethod() should be implemented in the sub class. if Creator provides default factoryMethod() implementation.  All object are currently known so that the Creator class create the known classes. The factoryMethod() method is intended for the future change.  Parameterized factory methods The factoryMethod() method obtains the object ID for creation, and creates the objects according the delivered ID. Product *Creator::factoryMethod(ProductID id) { if ( id == MINE ) return new MyProduct; if ( id == YOURS ) return new YourProduct; } 21

22 Factory Method Spec. -7  Language-specific variants and issues Diverse factoryMethod() can be existed according to the programming language. E.g., Smalltalk  Using templates to avoid subclassing C++ allows one to use template, so that the ConcreateCreator class is not needed to define repeatedly. class Creator { public: virtual Product* CreateProduct() = 0; }; template class StandardCreator: public Creator { public: virtual Product* CreateProduct() { return new TheProduct; } }; class MyProduct : public Product { public: MyProduct(); //... }; StandardCreator myCreator; 22

23 Factory Method Spec. -8  naming convention Need to define the naming convention for the factoryMethod() method. create??(), make??(), … E.g.,) MacApp Macintosh application –Use the DoMake prefix like Class *DoMakeClass() as the factoryMethod() method in the framework. How about you? 23

24 Factory Method Spec. -9  Known Uses  The factory method pattern is used broadly with Application, Document and View mentioned in the Motivation. ET++ system, MacApp of Macintosh, MFC framework of Visual Studio Smalltalk-80 Model/View/Controller framework  CORBA Orbix ORB system (from IONA Technologies): the pattern is used to create the proxy object for creating remote objects  Related Patterns  The pattern is used for implementing the Abstract Factory and Template Methods patterns.  The Prototype pattern can create an object without subclassing. However, the Prototype pattern needs additional the initialization method. 24

25 Abstract Factory: Motivation You take the user interface part for the commercial editor program. In order to broaden markets, the program shall support MS-Window based as well as Motif of the Linux based GUI. How can we make the program support two types of GUI in a single program? NotePad 파일 편집 서식 도움말 Editor Program MS-Windows Motif 25

26 Abstract Factory: Motivation -2  A Code for each GUI platform 코드 * MSWindow *win = new MSWindow; MSScrollbar *scrollbar = new MSScrollbar; MSMenu *menu = new MSMemu; MSMenuItem *i1 = new MSMenuItem; win->addScrollbar(scrollbar); menu->addItem(i1); win->addMenu(menu); … MotifWindow *win = new MotifWindow; MotifScrollbar *scrollbar = new MotifScrollbar; MotifMenu *menu = new MotifMemu; MotifMenuItem *i1 = new MotifMenuItem; win->addScrollbar(scrollbar); menu->addItem(i1); win->addMenu(menu); … * The source code is only intended for help one to understand the design patterns, which does not work in the MS-Windows or Motif UI. ? use “Abstract Factory” 26

27 Abstract Factory: Motivation -3  source code for creating platform specific GUI using the Factory Method pattern. #ifdef MSWINDOWS GUIFactory *factory = new MSFactory; #elif GUIFactory *factory = new MotifFactory; #end Window *win = factory->createWindow(); Scrollbar *scrollbar = factory->createScrollbar(); Menu *menu = factory->createMenu(); MenuItem *i1 = factory->createMenuItem(); win->addScrollbar(scrollbar); menu->addItem(i1); win->addMenu(menu); … A factory for MS- Window GUI A factory for Motif GUI 27

28 Abstract Factory: Motivation -4 28

29 Abstract Factory Spec.  Intent  It provides an interface for creating a family of related objects, without defining the classes in advance.  Also Known as  Kit  Motivation  previous  Applicability use this pattern when  The system should be operated regardless of the internal objects of the product.  The system should be configured as the one of the internal settings.  When a specific product is selected, the product features for the specific products should be enabled. 29

30 Abstract Factory Spec. -2  Structure 30

31 Abstract Factory Spec. -3  Participants  AbstractFactory (GUIFactory) Defines an interface for creating a product.  ConcreteFactory (MSFactory, MotifFactory) Plays a role for creating a real product.  AbstractProduct (Window, Scrollbar) Defines interfaces needed for each product.  ConcreteProduct (MotifWindow, MotifScrollbar) A Real product for conducting a concrete work  Client Uses an interface part defined in the AbstractFactory and AbstractProduct except the part for defining the ConcreteFactory class. 31

32 Abstract Factory Spec. -4  Collaboration  Generally, the one ConcreteFactory object should be used at one time during runtime.  The Client uses the part for creating the product-specific part.  Use the ConcreteFactory class if you want to use another types of product in the product family. #ifdef MSWINDOWS GUIFactory *factory = new MSFactory; #elif GUIFactory *factory = new MotifFactory; #end Window *win = factory->createWindow(); … 32

33 Abstract Factory Spec. -5  Consequences  Increase abstract The Client does not recognize what is the concrete Product class.  Easy to change product family Easy to change product family with just replacing the ConcreteFactory class at the initial or runtime.  Increase consistency in the products All product-specific parts are guaranteed from the creation of the same product factory, which increases consistency of the products.  Easy to define a new product family Not need to modify the previous source code.  It is difficult to define a new type of products. Need to have massive code change. 33

34 Abstract Factory Spec. -6  Implementation 1.Generally, only one ConcreteFactory class is needed for each product family. To support this, the Single patterns can be used together. 2.The prototype pattern can be used for creating ConcreteFactorys for massive product family. 3.When add a new product-specific part, adding new method “create??()” should be defined in the AbstractFactory class and all subclassed classes.  To handle this issue, the create(??) method can be used for getting the product-specific part as a parameter. 34

35 Abstract Factory Spec. -7  Known Uses  InterView system: the “Kit” postfix denotes the Abstract Factory (WidgetKit, DialogKit, LayoutKit, …)  ET++ system: Use the Abstract Factory for portability for diverse GUI environment(X Windows, SunView, …)  Related Patterns  The AbstractFactory is used as the Factory method pattern in general, however it can be implemented with the Prototype pattern.  The Singleton pattern can be used for maintaining a single ConcreteFactory object. 35

36 Builder: Motivation How can we design the program for converting RTF(Rich Text Format) file into diverse document file types(MsWord, HWP, ASCII, …)? RTF fileHWP MS-Word ASCII file How to Convert? 36

37 Builder: Motivation -2  RTF Reader does not access directly to Builder(MS-Word Builder, HWP Builder, …) in charge of converting. RTF file HWP MS-Word ASCII file RTF ReaderBuilder MS-Word Builder HWP Builder ASCII Builder 37

38 Builder: Motivation -3 38

39 Builder: Motivation -4  The ParseRTF() method for reading and analyzing RTF just sequently converts regardless of the targets.  Each builder (ASCIIBuilder, MSWordBuilder,…) creates and converts the Text objects according to each file format.  The Builder is separate from the reader  RTF Reader is responsible for parsing an RTF document  Each concrete builder is responsible for creating and assembling a text file. 39

40 Builder Spec.  Intent  Separating the construction of the object and its representation  Diverse representation can be possible with the single construction step.  Motivation  previous  Application use this pattern when  It is applicable when separating the algorithm, construction and its use part.  It supports a single construction and multiple constructions. 40

41 Builder Spec. -2  Structure 41

42 Builder Spec. -3  Participants  Builder (TextBuilder) Define an interface for building each part of the product  ConcreteBuilder (ASCIIBuilder, MSWordBuilder, HWPBuilder) Conduct the building part of each product object. Provide a method for returning a complete product object. (getASCIIText(), getMSWordText(), getHWPText())  Director (RTFReader) Construct an object using the builder interfact  Product (ASCIIText, MSWordText, HWPText) Complex object after the construction step. 42

43 Builder Spec. -4  Collaborations  Specify the Builder object for creating the director object in the client code.  Call the Builder when each part should be composed.  The Builder create the product part according to the call.  The client obtains the complete object from the Builder. 43

44 Builder Spec. -5 44

45 Builder Spec. -6  Consequences  The Builder pattern allows one to represent and change the internal of the targeting product.  It separates the building process and internal representation. The builder can be used in the different director(MSWordReader)  It is possible to manipulate precisely in building an object. The targeting object is created in the multiple steps so that it is possible to manipulate the building process precisely. 45

46 Builder Spec. -7  Known Uses  ET++ system: It is used in the RTF converter.  Smalltalk-80: Internal representation is built from parsing the SmallTalk source code.  Related Patterns  Builder Vs. Abstract Factory Builder pattern focuses on constructing a complex object step by step and returns the product as a final step. Abstract Factory pattern focuses on families of product and the product gets returned immediately.  The Composite pattern can be used together in the class of the product part from the Builder pattern. 46

47 Prototype: Motivation The company A selected you as a designer to upgrade the report management class library, which is the main product of the company. The upgrade mainly focuses on improving convenience of the clients for the system. Report ReportD ReportC ReportB ReportA … Client Code - The current state of the “report management class library” system: The developer access the Report object without directly accessing the real Report objects such as ReportA, ReportB and so forth, That is, clients cannot access the real Report objects from outside. [The Report Management Class Library] 47

48 Prototype: Motivation -2  The complaint of the customer(developer)  They use the specific Report object delivered from the library.  However, they need to create the same Report object with the delivered Report object.  For example, how can we copy the Report object to copy the report from the currently working Report object? The client cannot be aware of that the current working object is the ReportA object. // Client Code CopyReport(Report *rep) { Report *rep2 = new ??? } ReportA ReportB ReportC …. What?? 48

49 Prototype: Motivation -3  Solution #1 // Client Code CopyReport(Report *rep) { Report *rep2; switch ( rep->getType() ) { case REPORTA: rep2 = new ReportA; break; case REPORTB: rep2 = new ReportB; break; case REPORTC: rep3 = new ReportC; break; … } // use rep2. } [Problem] 1. Direct access to the Report object should be permitted to the client code. 2. The client code should know all inside of the Report object. 3. The client code should be changed whenever the Report object is updated. 4. The rep2 object can be created properly, the contents should be also copied accordingly. 49

50 Prototype: Motivation -4  Solution #2:  Delegate all of the copy related things to the original object, when the specific object should be copied. // Client Code CopyReport(Report *rep) { Report *rep2 = rep->clone(); // use rep2 … } The clone method provides a feature of creating the same object with itself. 1.The client code does not need to directly access to the real Report object. 2.The client code does not need to know the inside of the Report object. 3.The client code does not need to update whenever the Report object is changed. 4.All of the copy process in the clone method is carried in the Report Object. 50

51 Prototype: Motivation -5 Client Code Report clone() … ReportA clone() ReportB clone() ReportC clone() ReportD clone() [Report Management Class Library] Report *rep2 = rep1->clone(); return new ReportD(this); return new ReportB(this); 51

52 Prototype Spec.  Intent  Create a new object by cloning the prototypical object.  Motivation  previous  Applicability use this pattern when  You want to decide the real object at run-time. At the development time, the object is not decided yet.  You don’t want to make a factory class in charge of creating a family of product classes.  You want to clone the object without understanding the inside of the class. 52

53 Prototype Spec. -2  Structure 53

54 Prototype Spec. -3  Participants  Prototype (Report) The product class containing the clone() method  ConcretePrototype (ReportA, ReportB, …) The cloned product class It implements the clone() method for copying the real object.  Client The user class of the prototype when creating a new class.  Collaborations return b 54

55 Prototype Spec. -4  Consequences  Similar effect with Abstract Factory & Builder patterns The client does not need to know the concrete product class at the development time. When changing the set of the concrete product classes, the client code does not need to change.  The system can be more flexible, as the prototype object can be replaced into others at runtime.  The factory class does not need because the prototype object already provide a object creation feature. 55

56 Prototype Spec. -5  Implementation  Effective for the static language. The prototype pattern is useful for the object oriented programming language(e.g., C++) to decide the object type at runtime.  Prototype manager You can create the prototype manager to maintain the prototype objects.  Implementation of the Clone() method “shallow copy versus deep copy” problem Which one is effective?  Initializing clones If you want to initialize some of the attributes in the clone() method? Make the initialize() method and call it in the clone() method. 56

57 Prototype Spec. -10  Known Uses -Various systems uses this pattern Ivan Sutherland’s Sketchpad System ThingLab ET++ System Mode Composer Unidraw drawing framework  Related Patterns -The Abstract Factory and Prototype patterns are competitive for the same problem. -Compositional use of the prototype pattern provides several benefits in the use of the Composite and Decorator patterns. 57

58 Singleton: Motivation You are developing the Audio Class for controlling the audio device. The audio device should be used exclusively, so the only one Audio class should be existed in the whole system. However, your partners frequently forget this so that the system is exposed to the faults. What is the solution for this? You are developing the Audio Class for controlling the audio device. The audio device should be used exclusively, so the only one Audio class should be existed in the whole system. However, your partners frequently forget this so that the system is exposed to the faults. What is the solution for this? Audio Class // Client Code Audio *a = new Audio; … Audio *b = new Audio; … // Client Code Audio *a = new Audio; … Audio *b = new Audio; … a a b b Objects More than one objects should not be existed in the system. 58

59 Singleton: Motivation -2  Solution #1  All attributes and methods are defined in the class when the system does not need to maintain more than two objects.  That is, remove the object and use the class instead of it! // Client Code Audio::open();.. Audio::sound();.. Audio::close(); // Client Code Audio::open();.. Audio::sound();.. Audio::close(); Audio Class open() close() sound() Audio Class open() close() sound() 59

60 Singleton: Motivation -3  Implementation of the Solution #1 class Audio { public: static void initialize(); static void open(); static void close(); static void sound(); static void setVolume(int vol); private: static int _volume; }; int Audio::_volume = 50; // Client Code … Audio::initialize(); Audio::open(); Audio::setVolume(20); Audio::sound(“ding.wav”); … Audio::close(); static: Attributes and methods of the class 60

61 Singleton: Motivation -4  Solution #2  New the instance() method instead of the new keyword  The method returns the new Audio object if the Audio object is not existed.  If the object is existed, the method return the existing object. Audio Class Client Code Audio *a = Audio::Instance(); … Audio *b = Audio::Instance(); … Client Code Audio *a = Audio::Instance(); … Audio *b = Audio::Instance(); … audio object 61

62 Singleton: Motivation -5  Implementation of the Solution #2 class Audio { public: static Audio *Instance(); protected: Audio(); private: static Audio *_instance; }; Audio * Audio::_instance = NULL; Audio * Audio::Instance() { if ( _instance == NULL ) _instance = new Audio; return _instance; } static: Attributes/method The protected constructor? Static attribute for the instance Create a new object if the object is not existed. Return _instance 62

63 Singleton: Motivation -6  Solution #1 vs. #2  The second solution is more flexible. The virtual function can be used –(the static member variable cannot be the virtual function) It is possible to manage more than one objects. 63

64 Singleton Spec.  Intent  It guarantee the existence of the only one object in the entire system.  Motivation  previous  Applicability use this pattern when  The only one class instance should be existed in the system. Also, the instance should be accessed in the whole system. 64

65 Singleton Spec. -2  Structure  Participants  Singleton The client code should define the instance() method for accessing only one instance. It is in charge of creating and maintaining the only one instance of itself. 65

66 Singleton Spec. -3  Collaboration  The client can access the singleton class via the Instance() method.  Consequences  Controlled access to sole instance Access to the client can be controlled because the singleton class maintains the unique instance.  Reduced name space The global variable can be reduced because the singleton class permit one to access the unique instance globally. 66

67 Singleton Spec. -4  Collaboration  Permit refinement of operations and representation The Singleton class can be subclassed.  Permits a variable number of instances It is possible to change the number of instances in the Singleton class.  More flexible than class operations Refer to motivation -6. slide 67

68 Singleton Spec. -4  Implementation  Ensuring a unique instance Hide the new operation: The client code cannot instantiate the class through the new operation, as the accessibility of the constructor is defined as protected. Instance(): Through this operation, the client code can access to the instance. The instantiated class is stored in the static attribute of the class. class Singleton { public: static Singleton* Instance(); protected: Singleton(); private: static Singleton* _instance; }; Singleton* Singleton::_instance = NULL; Singleton* Singleton::Instance() { if (_instance==NULL) _instance = new Singleton; return _instance; } 68


Download ppt "1 DesignPattern-3 Creational Patterns Suntae Kim Kangwon National University"

Similar presentations


Ads by Google