design patterns in c++ - structural...

62
Design Patterns in C++ Structural Patterns Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant’Anna – Pisa March 23, 2011 G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 1 / 54

Upload: others

Post on 28-Jul-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Design Patterns in C++Structural Patterns

Giuseppe Liparihttp://retis.sssup.it/~lipari

Scuola Superiore Sant’Anna – Pisa

March 23, 2011

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 1 / 54

Page 2: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Introduction to Structural Patterns

Structural patterns are concerned with how classes and objectsare composed to for larger structures.Two kinds of “composition”:

static composition though inheritanceA class functionality is extended by deriving a new class andoverloading polymorphic methods, or by adding new methodsA class can mix the functionality of two classes through multipleinheritanceA class can implement multiple interfaces through interfaceinheritance

dynamic composition through associationsan object holds a pointer to another objectan object delegates part of its functionality to another objectan object can be composed by several smaller objects in manydifferent ways

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 2 / 54

Page 3: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Outline

1 Adapter pattern

2 Bridge

3 Composite pattern

4 Decorator

5 Proxy

6 Comparison

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 3 / 54

Page 4: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Motivation

We have implemented a toolkit to draw graphics objectsthe base class is Graphic, then we have CompositeGraphic,andLine, Polygon, etc.(see the Composite example)

We would like to add a TextBox, but it is difficult to implement

So we decide to buy an off-the-shel library that implementsTextBox

However, TextBox does not derive from Graphic.and we don’t have their source code

How to include it in our framework?

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 4 / 54

Page 5: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Options

We have two optionsImplement a TextShape class that derives from Graphic andfrom TextBox, reimplementing part of the interfaceImplement a TextShape class that derives from Graphic, andholds an object of type TextBox inside

These two represent the two options for the Adapter pattern

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 5 / 54

Page 6: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Multiple Inheritance option

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 6 / 54

Page 7: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Composition Option

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 7 / 54

Page 8: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Example

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 8 / 54

Page 9: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Another example

Suppose we are given the class:

class DocManager {public:

...void printDocument();void saveDocument();...

};

which is responsible for opening, closing, saving, and printing textdocuments

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 9 / 54

Page 10: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Another example

Suppose we are given the class:

class DocManager {public:

...void printDocument();void saveDocument();...

};

which is responsible for opening, closing, saving, and printing textdocumentsNow suppose we want to build a word-processing application:

Graphical user interface that allows, among other things, users tosave the file by clicking a Save button and to print the file byclicking a Print button.Details of saving and printing are handled by the class DocManager

Key problem: How to design class Button so that its instancescan collaborate with instances of class DocManager

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 9 / 54

Page 11: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Example – cont.

Observe: Two instances and one link:“print button” object of class Button“document manager” object of class DocManagerButton press should invoke printDocument() operation

Question: How might one design classes Button andDocManager to support this link?

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 10 / 54

Page 12: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Bad design

class Button {protected:

DocManager* target;void monitorMouse() {

...if (/* mouse click */) {

target->printDocument();}...

}...

};

Why this is a bad design?

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 11 / 54

Page 13: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Comments

Observe: To invoke printDocument() operation, Buttonneeded to know the class (DocManager) of the target object.However:

Button should not care that target is a DocManagerNot requesting information from targetMore like sending a message to say: “Hey, I’ve been pressed!. Godo something!”

Question: How can we design Button to send messages toobjects of arbitrary classes?;

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 12 / 54

Page 14: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Use interface class

class ButtonListener {public:

virtual void buttonPressed(const string&) = 0;};

This interface declares the messages that an object must be ableto handle in order to collaborate with a Button

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 13 / 54

Page 15: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

A better design

class Button {public:

Button(const string& lab) :label(lab), target(0) {}

void setListener(ButtonListener* blis) {target=blis;

}

protected:string label;ButtonListener* target;

void monitorMouse() {...if(/* mouse click */) {

if (target)target->buttonPressed(label);

}...

}};

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 14 / 54

Page 16: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Collaborator

Collaborator: any object that implements the ButtonListenerinterface

Collaborator must register interest in press events

What if DocManager is already written and tested and does notimplements interface ButtonListener?

Use the adapter interface

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 15 / 54

Page 17: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Collaborator

Collaborator: any object that implements the ButtonListenerinterface

Collaborator must register interest in press events

What if DocManager is already written and tested and does notimplements interface ButtonListener?

Use the adapter interface

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 15 / 54

Page 18: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Advantages

Class Button very reusableWe can understand the Button–ButtonListener collaborationwith little knowledge of Button and no knowledge of DocManager

Example of separation of concerns

Clear mechanism for adapting arbitrary class to implement theButtonListener interfaceRather than thinking of a program as a sequence of steps thatcompute a function We think of a program as comprising twoparts: initialization and then interaction

Initialization involves the allocation of objects and the assembly ofobjects into collaborations;Interaction involves the interaction of objects with other objects bysending messages back and forth

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 16 / 54

Page 19: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Which structure to use?

Multiple inheritance:Expose interfaces of the adaptee to clientsAllow the adapter to be used in places where an adaptee isexpected

CompositionDoes not expose interfaces of the adaptee to clients (safer)In places that an adaptee is expected, the adapter needs to providea function getAdaptee() to return the pointer to the adapteeobject.

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 17 / 54

Page 20: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Outline

1 Adapter pattern

2 Bridge

3 Composite pattern

4 Decorator

5 Proxy

6 Comparison

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 18 / 54

Page 21: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Motivation

Suppose that a general concept can have more than onealternative implementation

The window example, where there are different types of windows(icon, dialogue, framed, etc.), and they can be implemented indifferent windows managersA communication channel can be implemented on top of severalprotocols

The natural way to handle this situation is by using inheritanceHowever, it may sometimes happen that the same abstractionmust be extended across two or more orthogonal directions

In the case of the window manager, suppose that you can haveseveral OS platforms, and on each platform, several differentwindow classesIn the case of a communication system, two orthogonal conceptsare again the OS and the protocol

Using only inheritance leads to a multiplication of different classes

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 19 / 54

Page 22: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Separation of concerns

Inheritance is static:The client will depend upon a specific platformWhenever a client creates a window, it must select the correct classdepending on the platform (similar problem of the abstract factory)

Adding a new look-and-feel requires adding many different classes

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 20 / 54

Page 23: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Bridge pattern

Still use inheritance, but use a different class hierarchy for eachorthogonal extension

One class hierarchy for each different window typeOne class hierarchy for each window manager

All operations on windows must be implemented in terms of“basic” operations

These basic operations can have several differentimplementations on the different window managers

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 21 / 54

Page 24: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

UML Structure

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 22 / 54

Page 25: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

An example

In this example, we show how to use the bridge to generalize thetype of connection, independently of the OS and of the protocol(TCP or UDP)

The application has (soft) real-time constraints, and we would alsolike to have error correction and retransmission when possible

Initially the application will run on a local network, later it may bepossible to transmit on a wide area network

The idea is that the user should be able to easily change from aTCP to a UDP and vice versa

Also, the application must be portable across several OS andRTOS

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 23 / 54

Page 26: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Net connections

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 24 / 54

Page 27: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Server

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 25 / 54

Page 28: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Extensions

The client is not totally independent from the protocol

TCP needs a “Server” on a passive socket, which returns aNetConnection

while UDP can just wait for a message on a certain port of aregular NetConnectionThere are other ways to abstract from the OS

For example, the Facade pattern, which consists of an interface tocentralize all OS abstractions (threads, semaphores, etc.)In such a case, the Bridge Pattern is simplified, but still useful,because it decouples the protocol

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 26 / 54

Page 29: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Consequences

Decoupling interface and implementationAn implementation is not bound permanently to an interfaceNo compile-time dependencies, because changing animplementation does not require to re-compile the abstractions andits clients

Improved extensibilityAbstractions and implementers can be extended independently

Hiding implementation detailsHow to create, and who creates the right implementer object?

Use a factory object, that knows all implementation details of theplatform, so that the clients and the abstraction are completelyindependent of the implementation

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 27 / 54

Page 30: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Outline

1 Adapter pattern

2 Bridge

3 Composite pattern

4 Decorator

5 Proxy

6 Comparison

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 28 / 54

Page 31: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Composite pattern

We must write a complex program that has to treat several objectin a hierarchical way

Objects are composed together to create more complex objectsFor example, a painting program treats shapes, that can becomposed of more simple shapes (lines, squares, triangles, etc.)Composite objects must be treated like simple onesAnother example: a word processor, which allows the user tocompose a page consisting of letters, figures, and compositions ofmore elementary objects

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 29 / 54

Page 32: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Composite pattern

We must write a complex program that has to treat several objectin a hierarchical way

Objects are composed together to create more complex objectsFor example, a painting program treats shapes, that can becomposed of more simple shapes (lines, squares, triangles, etc.)Composite objects must be treated like simple onesAnother example: a word processor, which allows the user tocompose a page consisting of letters, figures, and compositions ofmore elementary objects

Requirements:Treat simple and complex objects uniformly in code – move, erase,rotate and set color work on allSome composite objects are defined statically (wheels), whileothers dynamically (user selection)Composite objects can be made of other composite objects

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 29 / 54

Page 33: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Solution

All simple objects inherit from a common interface, say Graphic:

class Graphic {public:

virtual void move(int x, int y) = 0;virtual void setColor(Color c) = 0;virtual void rotate(double angle) = 0;

};

The classes Line, Circle and others inherit Graphic and addspecific features (radius, length, etc.)

class CompositeGraphic: public Graphic,

public list<Graphic>{

void rotate(double angle) {for (int i=0; i<count(); i++)

item(i)->rotate();}

}

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 30 / 54

Page 34: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

The solution – II

Since a CompositeGraphic is a list, it had add(), remove()and count() methods

Since it is also a Graphic, it has rotate(), move() andsetColor() too

Such operations on a composite object work using a “forall” loop

Works even when a composite holds other composites – results ina tree-like data structure

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 31 / 54

Page 35: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

The solution – III

Example of creating a composite

CompositeGraphic *cg;cg = new CompositeGraphic();cg->add(new Line(0,0,100,100));cg->add(new Circle(50,50,100));cg->add(t); // dynamic text graphiccg->remove(2);

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 32 / 54

Page 36: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

UML representation

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 33 / 54

Page 37: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Participants

Component (Graphic)declares the interface for objects in the compositionimplements default behaviour for the interface common to allclasses, as appropriatedeclares an interface for accessing and managing its childcomponents(optional) defines an interface for accessing a component’s parentin the recursive structure, and implements it if that’s appropriate

Leaf (Rectangle, Line, Text, etc.)represents leaf objects in the composition. A leaf has no childrendefines behaviour for primitive objects in the composition

Composite (Picture)defines behaviour for components having childrenstores child componentsimplements child-related operations in the Component interface

Clientmanipulates objects in the composition through the Componentinterface

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 34 / 54

Page 38: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Trade-off between transparency and safety

Although the Composite class implements the Add and Removeoperations for managing children, an important issue in theComposite pattern is which classes declare these operations inthe Composite class hierarchy

For transparency, define child management code at the root of thehierarchy. Thus, you can treat all components uniformly. It costsyou safety, however, because clients may try to do meaninglessthings like add and remove objects from leaves

For safety, define child management in the Composite class.Thus, any attempt to add or remove objects from leaves will becaught at compile-time. But you lose transparency, becauseleaves and composites have different interfaces

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 35 / 54

Page 39: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Composite for safety

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 36 / 54

Page 40: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Known uses

Document editing programs

GUI (a form is a composite widget)

Compiler parse trees (a function is composed of simplerstatements or function calls, same for modules)

Financial assets can be simple (stocks, options) or a compositeportfolio

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 37 / 54

Page 41: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Outline

1 Adapter pattern

2 Bridge

3 Composite pattern

4 Decorator

5 Proxy

6 Comparison

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 38 / 54

Page 42: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Motivation

Sometimes we need to add responsibilities to individual objects(rather than to entire classes)

For example, in a GUI, add borders, or additional behaviours likescrollbar, to a widget

Inheritance approachWe could let the class Widget inherit from a Border classNot flexible, because for any additional responsibility, we must addadditional inheritanceNot flexible because is static: the client cannot control dynamicallywhether to add or not add the border

Composition approachEnclose the component into another object which additionallyimplements the new responsibility (i.e. draws the border)More flexible, can be done dynamicallyThe enclosing object is called decorator (or wrapper)

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 39 / 54

Page 43: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Example

A TextView object which displays text in a window

TextView class has no scrollbars by default

we add a ScrollDecorator to attach scrollbars to a TextViewobject

What if we also want a border?

Well, let’s use a BorderDecorator!

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 40 / 54

Page 44: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Example

A TextView object which displays text in a window

TextView class has no scrollbars by default

we add a ScrollDecorator to attach scrollbars to a TextViewobject

What if we also want a border?

Well, let’s use a BorderDecorator!

b:BorderDecorator

component

s:ScrollDecorator

component

t:TextView

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 40 / 54

Page 45: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

UML structure for Decorator

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 41 / 54

Page 46: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Description

VisualComponent is the the abstract class all components mustcomply to

From it, many different component classes derive with specificbehavioursOne of these classes is the Decorator which does nothing butwrapping another component and forwarding all requests to it

In the previous example, the Decorator class must forward allrequests of draw() to its component:

void Decorator::draw() {component->draw();

}

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 42 / 54

Page 47: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Decorators internals

All decorators classes must derive from Decorator,implementing the additional interface (scrollTo(),drawBorder(), etc.)

The draw() function is overridden to add the additional behavior

void BorderDecorator::draw() {Decorator::draw();drawBorder();

}

what the client will see will be the interface of theVisualComponent, plus the interface of the most externaldecorator

The key property is the any decorator implements the sameinterface of any other component

therefore, from the client point of view, it does not matter if anobject is decorated or not

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 43 / 54

Page 48: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Notes

When to useTo add responsibilities to individual object dynamically andtransparentlyWhen extension by sub-classing is impractical

Don’t use it the component class has large interfaceImplementation becomes too heavy (all methods must bere-implemented by forwarding to the internal component

When there are many “decoration options” you may end up with alot of small classes

The library may become more complex to understand and to usedue to the large number of classes

Where it is usedIn the Java IO library, the most basic classes perform rawinput/outputmore sophisticated I/O though decorators (i.e.BufferedInputStream, LineNumberInputStream, are alldecorators of InputStream)

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 44 / 54

Page 49: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Outline

1 Adapter pattern

2 Bridge

3 Composite pattern

4 Decorator

5 Proxy

6 Comparison

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 45 / 54

Page 50: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Proxy

Provide a surrogate or placeholder for another object tocontrol access to it

Some times it is impossible, or too expensive, to directly accessan object

Maybe the object is physically on another PC (in distributedsystems)In other cases, the object is too expensive to create, so it may becreated on demand

In such cases, we could use a placeholder for the object, that iscalled Proxy

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 46 / 54

Page 51: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Example

Suppose that a text document can embed images

Some of these can be very large, and so expensive to create andvisualize

on the other hand the user wants to load the document as soon aspossible

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 47 / 54

Page 52: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Example

Suppose that a text document can embed images

Some of these can be very large, and so expensive to create andvisualize

on the other hand the user wants to load the document as soon aspossible

the solution could be to use a “similar object” that has the samemethods as the original image objects

the object will start loading and visualizing the image only whennecessary (for example, on request for draw()), and in themeanwhile could draw a simple white box in its placeholder

it can also return the size of the image (height and width) that it iswhat is needed to format the rest of the document

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 47 / 54

Page 53: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

The structure

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 48 / 54

Page 54: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Generalization

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 49 / 54

Page 55: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Participants

Proxy (ImageProxy)maintains a reference that lets the proxy access the real subject. Itsinterface must be the same as the one of the RealSubject.provides an interface identical to Subject’s so that a proxy can besubstituted for the real subjectcontrols access to the real subject and may be responsible forcreating and deleting itother responsibilities depends on the kind of proxy

Subject (Graphic)defines the common interface for RealSubject and Proxy so that aproxy can be used anywhere a RealSubject is expected

RealSubject (Image)defines the real object that the proxy represents

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 50 / 54

Page 56: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Applicability

Proxy is applicable whenever there is the need for a moresophisticated reference to an object that a simple pointer

A remote proxy provides a local representative for an object in adifferent address spacea virtual proxy creates an expensive object on demand (like in theexample)a protection proxy controls access to the original object.Protection proxies are useful when objects should have differentaccess rightsA smart reference is a replacement for a bare pointer (seeshare_ptr or auto_ptr)implement copy-on-write behaviour when copying large objects

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 51 / 54

Page 57: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Outline

1 Adapter pattern

2 Bridge

3 Composite pattern

4 Decorator

5 Proxy

6 Comparison

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 52 / 54

Page 58: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Comparison of structural patterns

Many of the patterns we have seen have very similar classdiagrams

Therefore, the structure is quite similarthe basic idea is to favour composition for extending functionality,and use inheritance to make interfaces uniform, and this is why theylook similarhowever, the intent of these patterns is different

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 53 / 54

Page 59: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Comparison of structural patterns

Many of the patterns we have seen have very similar classdiagrams

Therefore, the structure is quite similarthe basic idea is to favour composition for extending functionality,and use inheritance to make interfaces uniform, and this is why theylook similarhowever, the intent of these patterns is different

Adapter versus BridgeBoth promote flexibility by providing a level of indirection to anotherobjectboth involve forwarding requests to this object from an interfaceother than its own

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 53 / 54

Page 60: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Comparison of structural patterns

Many of the patterns we have seen have very similar classdiagrams

Therefore, the structure is quite similarthe basic idea is to favour composition for extending functionality,and use inheritance to make interfaces uniform, and this is why theylook similarhowever, the intent of these patterns is different

Adapter versus BridgeBoth promote flexibility by providing a level of indirection to anotherobjectboth involve forwarding requests to this object from an interfaceother than its ownthe different is on their intentAdapter tries to adapt an existing interface to work with otherclasses; it is used after the class is availableBridge provides a bridge to a potentially large number ofimplementations; it is used before the classes are available

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 53 / 54

Page 61: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Composite / Decorator / Proxy

Composite and Decorator have similar recursive structureComposite is used to group objects and treat them as one singleobjectDecorator is used to add functionality to classes without usinginheritanceThese intents are complementarytherefore, these patterns are sometimes used in concert

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 54 / 54

Page 62: Design Patterns in C++ - Structural Patternsretis.sssup.it/~lipari/courses/oosd2010-2/05.structural.pdf · 2013-10-19 · Structural patterns are concerned with how classes and objects

Composite / Decorator / Proxy

Composite and Decorator have similar recursive structureComposite is used to group objects and treat them as one singleobjectDecorator is used to add functionality to classes without usinginheritanceThese intents are complementarytherefore, these patterns are sometimes used in concert

Decorator and Proxy are also similarThey both provide the same interface as the original objectHowever, Decorator is used to add functionalities; Decorators canbe wrapped one inside the otherProxy is used to control access

G. Lipari (Scuola Superiore Sant’Anna) Structural patterns March 23, 2011 54 / 54