Design Patterns CS 406 Software Engineering I Fall

  • Slides: 53
Download presentation
Design Patterns CS 406 Software Engineering I Fall 2001 Aditya P. Mathur Purdue University

Design Patterns CS 406 Software Engineering I Fall 2001 Aditya P. Mathur Purdue University October 30, 2001 CS 406: Design Patterns

Organization Patterns: Behavioral: Observer Structural: Façade Creational Abstract Factory Method Singleton Excellent reference: Design

Organization Patterns: Behavioral: Observer Structural: Façade Creational Abstract Factory Method Singleton Excellent reference: Design Patterns book by Erich Gamma, et al. , Addison-Wesley, 1994. CS 406: Design Patterns 2

Design Patterns [1] • A solution to a problem that occurs repeatedly in a

Design Patterns [1] • A solution to a problem that occurs repeatedly in a variety of contexts. • Each pattern has a name. • Use of each pattern has consequences. CS 406: Design Patterns 3

Design Patterns [2] • Generally at a “higher level” of abstraction. • Not about

Design Patterns [2] • Generally at a “higher level” of abstraction. • Not about designs such as linked lists or hash tables. • Generally descriptions of communicating objects and classes. CS 406: Design Patterns 4

Observer Pattern [1] • Need to separate presentational aspects with the data, i. e.

Observer Pattern [1] • Need to separate presentational aspects with the data, i. e. separate views and data. • Classes defining application data and presentation can be reused. • Change in one view automatically reflected in other views. Also, change in the application data is reflected in all views. • Defines one-to-many dependency amongst objects so that when one object changes its state, all its dependents are notified. CS 406: Design Patterns 5

Observer Pattern [2] Relative Percentages A B C D X 15 35 35 15

Observer Pattern [2] Relative Percentages A B C D X 15 35 35 15 Y 10 40 30 20 Z 10 40 30 20 Change notification Requests, modifications A D B C A B C D A=10% B=40% C=30% D=20% CS 406: Design Patterns Application data 6

Observer Pattern [3] observers Subject Observer Update() attach (Observer) detach (Observer) Notify () For

Observer Pattern [3] observers Subject Observer Update() attach (Observer) detach (Observer) Notify () For all x in observers{ x Update(); } Concrete Observer Concrete Subject subject Update() observer. State Get. State() Set. State() subject. State CS 406: Design Patterns observer. State= subject get. State(); 7

Class collaboration in Observer : Concrete. Subject : Concrete. Observer-1 : Concrete. Observer-2 Set.

Class collaboration in Observer : Concrete. Subject : Concrete. Observer-1 : Concrete. Observer-2 Set. State() Notify() Update() Get. State() CS 406: Design Patterns 8

Observer Pattern: Observer code class Subject; class observer { public: Abstract class defining the

Observer Pattern: Observer code class Subject; class observer { public: Abstract class defining the Observer interface. virtual ~observer; virtual void Update (Subject* the. Changed. Subject)=0; protected: observer (); }; Note the support for multiple subjects. CS 406: Design Patterns 9

Observer Pattern: Subject Code [1] class Subject { Abstract class defining the Subject interface.

Observer Pattern: Subject Code [1] class Subject { Abstract class defining the Subject interface. public: virtual ~Subject; virtual void Attach (observer*); virtual void Detach (observer*) ; virtual void Notify(); protected: Subject (); private: List <Observer*> *_observers; }; CS 406: Design Patterns 10

Observer Pattern: Subject Code [2] void Subject : : Attach (Observer* o){ _observers ->

Observer Pattern: Subject Code [2] void Subject : : Attach (Observer* o){ _observers -> Append(o); } void Subject : : Detach (Observer* o){ _observers -> Remove(o); } void Subject : : Notify (){ List. Iterator<Observer*> iter(_observers); for ( iter. First(); !iter. Is. Done(); iter. Next()) { iter. Current. Item() -> Update(this); } } CS 406: Design Patterns 11

Observer Pattern: A Concrete Subject [1] class Clock. Timer : public Subject { public:

Observer Pattern: A Concrete Subject [1] class Clock. Timer : public Subject { public: Clock. Timer(); virtual int Get. Hour(); virtual int Get. Minutes(); virtual int Get. Second(); void Tick (); } CS 406: Design Patterns 12

Observer Pattern: A Concrete Subject [2] Clock. Timer : : Tick { // Update

Observer Pattern: A Concrete Subject [2] Clock. Timer : : Tick { // Update internal time keeping state. // gets called on regular intervals by an internal timer. Notify(); } CS 406: Design Patterns 13

Observer Pattern: A Concrete Observer [1] class Digital. Clock: public Widget, public Observer {

Observer Pattern: A Concrete Observer [1] class Digital. Clock: public Widget, public Observer { public: Digital. Clock(Clock. Timer*); virtual ~Digital. Clock(); Override Observer operation. virtual void Update(Subject*); virtual void Draw(); Override Widget operation. private: Clock. Timer* _subject; } CS 406: Design Patterns 14

Observer Pattern: A Concrete Observer [2] Digital. Clock : : Digital. Clock (Clock. Timer*

Observer Pattern: A Concrete Observer [2] Digital. Clock : : Digital. Clock (Clock. Timer* s) { _subject = s; _subject Attach(this); } Digital. Clock : : ~Digital. Clock() { _subject->Detach(this); } CS 406: Design Patterns 15

Observer Pattern: A Concrete Observer [3] void Digital. Clock : : Update (subject* the.

Observer Pattern: A Concrete Observer [3] void Digital. Clock : : Update (subject* the. Changed. Subject ) { If (the. Changed. Subject == _subject) { Draw(); } Check if this is the clock’s subject. } void Digital. Clock : : Draw () { int hour = _subject->Get. Hour(); int minute = _subject->Ge. Minute(); // etc. // Code for drawing the digital clock. } CS 406: Design Patterns 16

Observer Pattern: Main (skeleton) Clock. Timer* timer = new Clock. Timer; Digital. Clock* digital.

Observer Pattern: Main (skeleton) Clock. Timer* timer = new Clock. Timer; Digital. Clock* digital. Clock = new Digital. Clock (timer); CS 406: Design Patterns 17

When to use the Observer Pattern? • When an abstraction has two aspects: one

When to use the Observer Pattern? • When an abstraction has two aspects: one dependent on the other. Encapsulating these aspects in separate objects allows one to vary and reuse them independently. • When a change to one object requires changing others and the number of objects to be changed is not known. • When an object should be able to notify others without knowing who they are. Avoid tight coupling between objects. CS 406: Design Patterns 18

Observer Pattern: Consequences • Abstract coupling between subject and observer. Subject has no knowledge

Observer Pattern: Consequences • Abstract coupling between subject and observer. Subject has no knowledge of concrete observer classes. (What design principle is used? ) • Support for broadcast communication. A subject need not specify the receivers; all interested objects receive the notification. • Unexpected updates: Observers need not be concerned about when then updates are to occur. They are not concerned about each other’s presence. In some cases this may lead to unwanted updates. CS 406: Design Patterns 19

Facade Pattern: Problem Client Classes Need to communicate with Subsystem classes CS 406: Design

Facade Pattern: Problem Client Classes Need to communicate with Subsystem classes CS 406: Design Patterns 20

Facade Pattern: Solution Client Classes Facade Subsystem classes CS 406: Design Patterns 21

Facade Pattern: Solution Client Classes Facade Subsystem classes CS 406: Design Patterns 21

Facade Pattern: Why and What? • Subsystems often get complex as they evolve. •

Facade Pattern: Why and What? • Subsystems often get complex as they evolve. • Need to provide a simple interface to many, often small, classes. But not necessarily to ALL classes of the subsystem. • Façade provides a simple default view good enough for most clients. • Facade decouples a subsystem from its clients. • A façade can be a single entry point to each subsystem level. This allows layering. CS 406: Design Patterns 22

Facade Pattern: Participants and Communication • Participants: Façade and subsystem classes • Clients communicate

Facade Pattern: Participants and Communication • Participants: Façade and subsystem classes • Clients communicate with subsystem classes by sending requests to façade. • Façade forwards requests to the appropriate subsystem classes. • Clients do not have direct access to subsystem classes. CS 406: Design Patterns 23

Facade Pattern: Benefits • Shields clients from subsystem classes; reduces the number of objects

Facade Pattern: Benefits • Shields clients from subsystem classes; reduces the number of objects that clients deal with. • Promotes weak coupling between subsystem and its clients. • Helps in layering the system. Helps eliminate circular dependencies. CS 406: Design Patterns 24

Example: A compiler Compiler Invocations Compile() Stream Bytecode. Stream Code. Generator Scanner Token Parser

Example: A compiler Compiler Invocations Compile() Stream Bytecode. Stream Code. Generator Scanner Token Parser Symbol Pnode. Builder Statement. Node RISCCodegenerator Pnode Expression. Node Stack. Machine. Codegenerator CS 406: Design Patterns 25

Façade Pattern: Code [1] class Scanner { // Takes a stream of characters and

Façade Pattern: Code [1] class Scanner { // Takes a stream of characters and produces a stream of tokens. public: Scanner (istream&); virtual Scanner(); virtual Token& Scan(); Private: istream& _input. Stream; }; CS 406: Design Patterns 26

Façade Pattern: Code [2] class parser { // Builds a parse tree from tokens

Façade Pattern: Code [2] class parser { // Builds a parse tree from tokens using the PNode. Builder. public: Parser (); virtual ~Parser() virtual void Parse (Scanner&, PNode. Builder&); }; CS 406: Design Patterns 27

Façade Pattern: Code [3] class Pnodebuilder { public: // Builds a parse tree incrementally.

Façade Pattern: Code [3] class Pnodebuilder { public: // Builds a parse tree incrementally. Parse tree // consists of Pnode objects. Pnodebuilder (); virtual Pnode* New. Variable ( // Node for a variable. Char* variable. Name ) const; virtual Pnode* New. Assignment ( // Node for an assignment. Pnode* variable, Pnode* expression ) const; // Similarly. . . more nodes. Private: Pnode* _node; }; CS 406: Design Patterns 28

Façade Pattern: Code [4] class Pnode { // An interface to manipulate the program

Façade Pattern: Code [4] class Pnode { // An interface to manipulate the program node and its children. public: // Manipulate program node. virtual void Get. Source. Position (int& line, int& index); // Manipulate child node. virtual void Add (Pnode*); virtual void Remove (Pnode*); // …. virtual void traverse (Codegenerator&); // Traverse tree to generate code. protected: PNode(); }; CS 406: Design Patterns 29

Façade Pattern: Code [5] class Code. Generator { // Generate bytecode. public: // Manipulate

Façade Pattern: Code [5] class Code. Generator { // Generate bytecode. public: // Manipulate program node. virtual void Visit (Statement. Node*); virtual void Visit (Expression. Node*); // …. Protected: Code. Generator (Bytecode. Stream&); Bytecode. Stream& _output; }; CS 406: Design Patterns 30

Façade Pattern: Code [6] void Expression. Node: : Traverse (Code. Generator& cg) { cg.

Façade Pattern: Code [6] void Expression. Node: : Traverse (Code. Generator& cg) { cg. Visit (this); List. Iterator<Pnode*> i(_children); For (i. First(); !i. Is. Done(); i. Next(); { i. Current. Item() Traverse(cg); }; }; CS 406: Design Patterns 31

Façade Pattern: Code [7] class Compiler { // Façade. Offers a simple interface to

Façade Pattern: Code [7] class Compiler { // Façade. Offers a simple interface to compile and // Generate code. public: Could also take a Code. Generator Compiler(); Parameter for increased generality. virtual void Compile (istream&, Bytecode. Stream&); } void Compiler: : Compile (istream& input, Bytecode. Stream& output) { Scanner scanner (input); Pnode. Builder builder; Parser parser; parser. Parse (scanner, builder); RISCCode. Generator generator (output); Pnode* parse. Tree = builder. Get. Root. Node(); parse. Tree Traverse (generator); } CS 406: Design Patterns 32

Facade Pattern: Another Example from POS [1] • Assume that rules are desired to

Facade Pattern: Another Example from POS [1] • Assume that rules are desired to invalidate an action: – Suppose that when a new Sale is created, it will be paid by a gift certificate – Only one item can be purchased using a gift certificate. – Hence, subsequent enter. Item operations must be invalidated in some cases. (Which ones? ) How does a designer factor out the handling of such rules? CS 406: Design Patterns 33

Facade Pattern: Another Example [2] • Define a “rule engine” subsystem (e. g. POSRule.

Facade Pattern: Another Example [2] • Define a “rule engine” subsystem (e. g. POSRule. Engine. Facade). • It evaluates a set of rules against an operation and indicates if the rule has invalidated an operation. • Calls to this façade are placed near the start of the methods that need to be validated. – Example: Invoke the façade to check if a new sales. Line. Item created by make. Line. Item is valid or not. (See page 370 of Larman. ) CS 406: Design Patterns 34

Toolkits and Frameworks Main body of an Application Reuse the main body of an

Toolkits and Frameworks Main body of an Application Reuse the main body of an Application and write the code it calls Calls a procedure or A method Toolkit Defines the architecture Of the application Framework Toolkits: Collection of related and reusable classes e. g. C++ I/O stream library Framework: A set of cooperating classes that make up a reusable design for a specific class of applications e. g. drawing, compilers, CAD/CAM etc. CS 406: Design Patterns 35

Toolkits and Frameworks Advantages and disadvantages of using frameworks. 1. When using frameworks, what

Toolkits and Frameworks Advantages and disadvantages of using frameworks. 1. When using frameworks, what defines the architecture of the application? 2. What is more difficult to design: Application, toolkit, or frameworks? 3. How do changes in framework effect an application? 4. How do design patterns differ from frameworks? CS 406: Design Patterns 36

Abstract Factory: The Problem 1. Consider a user interface toolkit to support multiple lookand-feel

Abstract Factory: The Problem 1. Consider a user interface toolkit to support multiple lookand-feel standards. 2. For portability an application must not hard code its widgets for one look and feel. How to design the application so that incorporating new look and feel requirements will be easy? CS 406: Design Patterns 37

Abstract Factory Pattern: Solution[1] 1. Define an abstract Widget. Factory class. 2. This class

Abstract Factory Pattern: Solution[1] 1. Define an abstract Widget. Factory class. 2. This class declares an interface to create different kinds of widgets. 3. There is one abstract class for each kind of widget and concrete subclasses implement widgets for different standards. 4. Widget. Factory offers an operation to return a new widget object for each abstract widget class. Clients call these operations to obtain instances of widgets without being aware of the concrete classes they use. CS 406: Design Patterns 38

Abstract Factory: Solution[2] Widget. Factory Client Window Create. Scrollbar() Create. Window() Mac. Window WWindow

Abstract Factory: Solution[2] Widget. Factory Client Window Create. Scrollbar() Create. Window() Mac. Window WWindow Scroll. Bar WWidget. Factory Mac. Scroll. Bar One for each standard. CS 406: Design Patterns WScroll. Bar 39

Abstract Factory: Solution[2] Abstract. Factory Client Create. Scrollbar() Abstract. Product. A Create. Window() Product.

Abstract Factory: Solution[2] Abstract. Factory Client Create. Scrollbar() Abstract. Product. A Create. Window() Product. A 2 Product. A 1 Abstract. Product. B Concrete. Factory 1 Concrete. Factory 2 Create. Product. A() Product. B 2 Product. B 1 Create. Product. B() CS 406: Design Patterns 40

Abstract Factory Pattern: Participants and Communication • Abstract. Factory: Declares the interface for operations

Abstract Factory Pattern: Participants and Communication • Abstract. Factory: Declares the interface for operations to create abstract product objects • Concrete. Factory: Implements the operations to create concrete product objects. • Abstract. Product: Declares an interface for a type of product object. • Concrete. Product: Defines a product object to be created by the corresponding factory. • Client: Uses only the interface declared by the abstract. Factory and Abstract. Product classes. CS 406: Design Patterns 41

Abstract Factory Pattern: Code [1] class Maze. Factory { public: // Creates components of

Abstract Factory Pattern: Code [1] class Maze. Factory { public: // Creates components of mazes. // Builds rooms, walls, and doors. Maze. Factory(); virtual Maze* Make. Maze() const { return new Maze; } virtual Wall* Make. Wall() const // This factory is a collection of // factory methods. Also, this class // acts both as Abstract and Concrete // Factory { return new Wall; } virtual Wall* Make. Room(int n) const { return new Room; } // more methods. } CS 406: Design Patterns 42

Abstract Factory Pattern: Code [1] Maze* Maze. Game: : Create. Maze (Maze. Factory& factory)

Abstract Factory Pattern: Code [1] Maze* Maze. Game: : Create. Maze (Maze. Factory& factory) // Builds a maze. Maze* a. Maze = factory. Make. Maze(); Room* myroom = factory. Make. Room(1); Room* herroom = factory. Make. Room(2); Door* a. Door = factory. Make. Door(my. Room, her. Room) a. Maze Add. Room(my. Room) a. Maze Add. Room(her. Room) // More code to add walls. } CS 406: Design Patterns // One can also create a // Bombed. Maze. Factory with // different types of Rooms // and Walls. 43

Factory Method: The Problem [1] 1. Frameworks use abstract classes to define and maintain

Factory Method: The Problem [1] 1. Frameworks use abstract classes to define and maintain relationships between objects 2. Consider a framework for applications that present multiple documents to the user. A drawing application is an example. 3. This framework defines two abstract classes: application and document. These ought to be sub classed by clients for application specific implementation. 4. The application class will create and manage documents when required, e. g. when a New command is selected from the menu. CS 406: Design Patterns 44

Factory Method Pattern: The Problem [2] 5. Document sub class is application specific. Hence

Factory Method Pattern: The Problem [2] 5. Document sub class is application specific. Hence the Application class does not know what kind of document to create! 6. Problem: The framework must instantiate classes but it only knows about the abstract classes, which it cannot initiate! CS 406: Design Patterns 45

Factory Method Pattern: Solution[1] 1. The Factory Method pattern encapsulates the knowledge of which

Factory Method Pattern: Solution[1] 1. The Factory Method pattern encapsulates the knowledge of which Document subclass to create and moves this knowledge out of the framework. 2. Application subclasses redefine an abstract Create. Doc() method to return the appropriate Document subclass. 3. When an Application is instantiated, it can instantiate application specific Documents without knowing their class. CS 406: Design Patterns 46

Factory Method: Solution[2] Factory method docs Document 1 * Application Create. Doc() New. Doc()

Factory Method: Solution[2] Factory method docs Document 1 * Application Create. Doc() New. Doc() Open() Close() Save() My. Application Create. Doc() My. Document* doc=Create. Doc(); docs. Add(doc); doc Open(); CS 406: Design Patterns 47

Factory Method Pattern: Structure Creator Product Factory. Method() Some. Operation() product=Factory method Concrete. Creator

Factory Method Pattern: Structure Creator Product Factory. Method() Some. Operation() product=Factory method Concrete. Creator Factory. Method() Concrete. Product Return new Concrete. Product CS 406: Design Patterns 48

Factory Method Pattern: Participants and Communication • Product (Document): Defines the interface of objects

Factory Method Pattern: Participants and Communication • Product (Document): Defines the interface of objects the factory method creates. • Concrete. Product (My. Document): Implements the Product interface. • Creator (Application): Declares factory method which returns an object of type Product. Also, may define the factory method to create a Product object. • Concrete. Creator (My. Application): Overrides the factory method to return an instance of a Concrete. Product. CS 406: Design Patterns 49

Other Patterns: Singleton • Used to ensure that a class has only one instance.

Other Patterns: Singleton • Used to ensure that a class has only one instance. For example, one printer spooler object, one file system, one window manager, etc. • One may use a global variable to access an object but it does not prevent one from creating more than one instance. • Instead the class itself is made responsible for keeping track of its instance. It can thus ensure that no more than one instance is created. This is the singleton pattern. CS 406: Design Patterns 50

Singleton Structure Singleton static unique. Instance return uniqueinstance singleton. Data static Instance() Singleton. Op()

Singleton Structure Singleton static unique. Instance return uniqueinstance singleton. Data static Instance() Singleton. Op() Get. Singleton. Data() CS 406: Design Patterns 51

Singleton Code [1] // Only one instance can ever be created. class Singleton {

Singleton Code [1] // Only one instance can ever be created. class Singleton { public: static Singleton* Instance(); protected: Singleton(); // Creation hidden inside Instance(). private: Static Singleton* _instance } // Cannot access directly. CS 406: Design Patterns 52

Singleton Code [2] Singleton* Singleton: : _instance=0; Singleton* Singleton: : Instance(){ if (_instance ==0)

Singleton Code [2] Singleton* Singleton: : _instance=0; Singleton* Singleton: : Instance(){ if (_instance ==0) { _instance=new Singleton; } Return _instance; } // Clients access the singleton // exclusively via the Instance member // function. CS 406: Design Patterns 53