You are on page 1of 53

Design Patterns

CS 406 Software Engineering I Fall 2001

Aditya P. Mathur

Purdue University

October 30, 2001

Organization
Patterns: Behavioral: Observer Structural: Faade Creational Abstract Factory Factory Method Singleton
Excellent reference: Design Patterns book by Erich Gamma, et al., Addison-Wesley, 1994.

CS 406: Design Patterns

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

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

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 Y Z 15 35 35 15 10 40 30 20 10 40 30 20 A B C D D

A B C

Change notification Requests, modifications

A=10% B=40% C=30% D=20%


CS 406: Design Patterns

Application data

Observer Pattern [3]


observers Subject
attach (Observer) detach (Observer) Notify ()

Observer
Update()

For all x in observers{ x Update(); } Concrete Observer subject

Concrete Subject
GetState() SetState() subjectState
CS 406: Design Patterns

Update() observerState

observerState= subject getState();


7

Class collaboration in Observer


:ConcreteSubject
:ConcreteObserver-1 :ConcreteObserver-2

SetState() Notify() Update() GetState() Update() GetState()


CS 406: Design Patterns 8

Observer Pattern: Observer code


class Subject;

class observer { public:


virtual ~observer;

Abstract class defining the Observer interface.

virtual void Update (Subject* theChangedSubject)=0;

protected:
observer ();

};

Note the support for multiple subjects.


CS 406: Design Patterns 9

Observer Pattern: Subject Code [1]


class Subject {

public:
virtual ~Subject;

Abstract class defining the Subject interface.

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 -> Append(o);

} void Subject :: Detach (Observer* o){


_observers -> Remove(o);

} void Subject :: Notify (){


ListIterator<Observer*> iter(_observers); for ( iter.First(); !iter.IsDone(); iter.Next()) {
iter.CurrentItem() -> Update(this);

CS 406: Design Patterns

11

Observer Pattern: A Concrete Subject [1]


class ClockTimer : public Subject { public:
ClockTimer(); virtual int GetHour(); virtual int GetMinutes(); virtual int GetSecond(); void Tick ();

CS 406: Design Patterns

12

Observer Pattern: A Concrete Subject [2]


ClockTimer :: 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 DigitalClock: public Widget, public Observer { public:
DigitalClock(ClockTimer*); virtual ~DigitalClock(); virtual void Update(Subject*); virtual void Draw();

Override Observer operation. Override Widget operation.

private:
ClockTimer* _subject; }

CS 406: Design Patterns

14

Observer Pattern: A Concrete Observer [2]

DigitalClock ::DigitalClock (ClockTimer* s) {


_subject = s; _subject Attach(this);

} DigitalClock ::~DigitalClock() {
_subject->Detach(this);

CS 406: Design Patterns

15

Observer Pattern: A Concrete Observer [3]

void DigitalClock ::Update (subject* theChangedSubject ) { If (theChangedSubject == _subject) { Draw();


}

} void DigitalClock ::Draw () { int hour = _subject->GetHour();

Check if this is the clocks subject.

int minute = _subject->GeMinute(); // etc. // Code for drawing the digital clock. }
CS 406: Design Patterns 16

Observer Pattern: Main (skeleton)

ClockTimer* timer = new ClockTimer;

DigitalClock* digitalClock = new DigitalClock (timer);

CS 406: Design Patterns

17

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 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 others 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 Patterns

20

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. Need to provide a simple interface to many, often small, classes. But not necessarily to ALL classes of the subsystem. Faade provides a simple default view good enough for most clients. Facade decouples a subsystem from its clients. A faade can be a single entry point to each subsystem level. This allows layering.
CS 406: Design Patterns 22

Facade Pattern: Participants and Communication


Participants: Faade and subsystem classes Clients communicate with subsystem classes by sending requests to faade. Faade 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 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
Compile() Stream Scanner BytecodeStream Parser CodeGenerator PnodeBuilder Pnode Symbol Token Invocations

StatementNode RISCCodegenerator StackMachineCodegenerator

ExpressionNode

CS 406: Design Patterns

25

Faade 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& _inputStream;

};

CS 406: Design Patterns

26

Faade Pattern: Code [2]


class parser { // Builds a parse tree from tokens using the PNodeBuilder.
public:
Parser (); virtual ~Parser() virtual void Parse (Scanner&, PNodeBuilder&);

};

CS 406: Design Patterns

27

Faade Pattern: Code [3]


class Pnodebuilder {
public: Pnodebuilder ();
virtual Pnode* NewVariable ( Char* variableName

// Builds a parse tree incrementally. Parse tree // consists of Pnode objects.

// Node for a variable.

) const;
virtual Pnode* NewAssignment ( Pnode* variable, Pnode* expression

// Node for an assignment.

) const; Private:
Pnode* _node;

// Similarly...more nodes.

};

CS 406: Design Patterns

28

Faade Pattern: Code [4]


class Pnode {
// An interface to manipulate the program node and its children. public: // Manipulate program node.
virtual void GetSourcePosition (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

Faade Pattern: Code [5]


class CodeGenerator {
public: // Manipulate program node.
virtual void Visit (StatementNode*); virtual void Visit (ExpressionNode*);

// Generate bytecode.

// . Protected:
CodeGenerator (BytecodeStream&); BytecodeStream& _output;

};

CS 406: Design Patterns

30

Faade Pattern: Code [6]


void ExpressionNode::Traverse (CodeGenerator& cg) {
cg.Visit (this);
ListIterator<Pnode*> i(_children); For (i.First(); !i.IsDone(); i.Next();{ i.CurrentItem() Traverse(cg);

}; };

CS 406: Design Patterns

31

Faade Pattern: Code [7]


class Compiler {
// Faade. Offers a simple interface to compile and // Generate code. public: Could also take a CodeGenerator Compiler(); Parameter for increased generality. virtual void Compile (istream&, BytecodeStream&); } void Compiler:: Compile (istream& input, BytecodeStream& output) { Scanner scanner (input); PnodeBuilder builder; Parser parser; parser.Parse (scanner, builder); RISCCodeGenerator generator (output); Pnode* parseTree = builder.GetRootNode(); parseTree Traverse (generator); }
CS 406: Design Patterns 32

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 enterItem 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. POSRuleEngineFacade). It evaluates a set of rules against an operation and indicates if the rule has invalidated an operation. Calls to this faade are placed near the start of the methods that need to be validated.
Example: Invoke the faade to check if a new salesLineItem created by makeLineItem is valid or not. (See page 370 of Larman.)

CS 406: Design Patterns

34

Toolkits and Frameworks


Main body of an Application
Calls a procedure or A method

Reuse the main body of an Application and write the code it calls
Defines the architecture Of the application

Toolkit

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 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 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. 2. Define an abstract WidgetFactory class. This class declares an interface to create different kinds of widgets. There is one abstract class for each kind of widget and concrete subclasses implement widgets for different standards. WidgetFactory 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

3.

4.

Abstract Factory: Solution[2]


WidgetFactory
CreateScrollbar() CreateWindow() MacWindow WWindow Window

Client

WWidgetFactory

ScrollBar

MacWidgetFactory

MacScrollBar One for each standard.


CS 406: Design Patterns

WScrollBar
39

Abstract Factory: Solution[2]


AbstractFactory
CreateScrollbar() CreateWindow()
ProductA2 ProductA1 AbstractProductA

Client

ConcreteFactory1

AbstractProductB

ConcreteFactory2

CreateProductA() CreateProductB()

ProductB2

ProductB1

CS 406: Design Patterns

40

Abstract Factory Pattern: Participants and Communication


AbstractFactory: Declares the interface for operations to create abstract product objects ConcreteFactory: Implements the operations to create concrete product objects. AbstractProduct: Declares an interface for a type of product object. ConcreteProduct: Defines a product object to be created by the corresponding factory. Client: Uses only the interface declared by the abstractFactory and AbstractProduct classes.
CS 406: Design Patterns 41

Abstract Factory Pattern: Code [1]


class MazeFactory {
public: MazeFactory();
virtual Maze* MakeMaze() const { return new Maze;} virtual Wall* MakeWall() const { return new Wall;} virtual Wall* MakeRoom(int n) const { return new Room;}

// Creates components of mazes. // Builds rooms, walls, and doors.

// This factory is a collection of // factory methods. Also, this class // acts both as Abstract and Concrete // Factory

// more methods. }
CS 406: Design Patterns 42

Abstract Factory Pattern: Code [1]


Maze* MazeGame:: CreateMaze (MazeFactory& factory) // Builds a maze. Maze* aMaze = factory.MakeMaze(); Room* myroom = factory.MakeRoom(1); Room* herroom = factory.MakeRoom(2); Door* aDoor = factory.MakeDoor(myRoom,herRoom) aMaze AddRoom(myRoom) aMaze AddRoom(herRoom) // More code to add walls. }
CS 406: Design Patterns

// One can also create a // BombedMazeFactory with // different types of Rooms // and Walls.
43

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 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 Document subclass to create and moves this knowledge out of the framework. Application subclasses redefine an abstract CreateDoc() method to return the appropriate Document subclass. When an Application is instantiated, it can instantiate application specific Documents without knowing their class.

2.

3.

CS 406: Design Patterns

46

Factory Method: Solution[2]


actory method

docs Document
Open() Close() Save() * 1

Application
CreateDoc() NewDoc() OpenDoc()

MyApplication MyDocument
CreateDoc() Document* doc=CreateDoc(); docs.Add(doc); doc Open();
CS 406: Design Patterns 47

Factory Method Pattern: Structure


Product Creator
FactoryMethod() SomeOperation() product=Factory method

ConcreteCreator ConcreteProduct
FactoryMethod()

Return new ConcreteProduct


CS 406: Design Patterns 48

Factory Method Pattern: Participants and Communication


Product (Document): Defines the interface of objects the factory method creates.

ConcreteProduct (MyDocument): 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.

ConcreteCreator (MyApplication): Overrides the factory method to return an instance of a ConcreteProduct.


CS 406: Design Patterns 49

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 uniqueInstance singletonData static Instance() SingletonOp() GetSingletonData() return uniqueinstance

CS 406: Design Patterns

51

Singleton Code [1]


class Singleton {
public: static Singleton* Instance(); protected: Singleton(); // Only one instance can ever be created.

// 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) { _instance=new Singleton; } Return _instance; }


// Clients access the singleton // exclusively via the Instance member // function.
CS 406: Design Patterns 53

You might also like