Design Patterns Structural Patterns. Adapter Convert the interface of a class into another interface clients expect Adapter lets classes work together.

Slides:



Advertisements
Similar presentations
Matt Klein. Decorator Pattern  Intent  Attach Additional responsibilities to an object by dynamically. Decorators provide a flexible alternative to.
Advertisements

1 Structural Design Patterns - Neeraj Ray. 2 Structural Patterns - Overview n Adapter n Bridge n Composite n Decorator.
02 - Structural Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.
Design Patterns Copyright © Vyacheslav Mukhortov, Nikita Nyanchuk-Tatarskiy, Copyright © INTEKS LLC,
C15: Design Patterns Gamma,Helm,Johnson,Vlissides (GOF)
PATTERNS -STRUCTURAL PATTERNS WATTANAPON G SUTTAPAK Software Engineering, School of Information Communication Technology, University of PHAYAO 1.
Bridge The decoupling of abstraction and implementation.
Façade Pattern Jeff Schott CS590L Spring What is a façade? 1) The principal face or front of a building 2) A false, superficial, or artificial appearance.
Software Design and Documentation Individual Presentation: Composite Pattern 9/11/03.
Chapter 8 Object Design Reuse and Patterns. Finding Objects The hardest problems in object-oriented system development are: –Identifying objects –Decomposing.
The Composite Pattern.. Composite Pattern Intent –Compose objects into tree structures to represent part-whole hierarchies. –Composite lets clients treat.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
PRESENTED BY SANGEETA MEHTA EECS810 UNIVERSITY OF KANSAS OCTOBER 2008 Design Patterns.
Client/Server Software Architectures Yonglei Tao.
Design Patterns.
The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
SOFTWARE DESIGN AND ARCHITECTURE
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
Design Patterns Part two. Structural Patterns Concerned with how classes and objects are composed to form larger structures Concerned with how classes.
Design Patterns: Structural Design Patterns
Design Pattern. The Observer Pattern The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Design Patterns CSCI 5801: Software Engineering. Design Patterns.
Computing IV Singleton Pattern Xinwen Fu.
SDP Structural Pattern. SDP-2 Structural Patterns Concerned with how classes and objects are composed to form large structures Class Patterns use.
Structural Design Patterns
ECE450S – Software Engineering II
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IV Structural Patterns.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns V More Structural Patterns.
Creational Patterns
08 - StructuralCSC4071 Structural Patterns concerned with how classes and objects are composed to form larger structures –Adapter interface converter Bridge.
Structural Patterns1 Nour El Kadri SEG 3202 Software Design and Architecture Notes based on U of T Design Patterns class.
Proxy.
DESIGN PATTERNS COMMONLY USED PATTERNS What is a design pattern ? Defining certain rules to tackle a particular kind of problem in software development.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Object Management. Constructors –Compiler-generated –The Initializer List –Copy Constructors –Single-arg (conversion ctors) The Assignment Operator.
CS 210 Final Review November 28, CS 210 Adapter Pattern.
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
The Bridge Pattern (Structural) “All problems in computer science can be solved by another level of indirection.” – Butler Lampson ©SoftMoore ConsultingSlide.
1 Advanced Object-oriented Design – Principles and Patterns Structural Design Patterns.
Bridge Bridge is used when we need to decouple an abstraction from its implementation so that the two can vary independently. This type of design pattern.
Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another using Arrays. How does one work with these.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
Watching the movie the hard way…. Page 256 – Head First Design Patterns.
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
CS 5150 Software Engineering Lecture 16 Program Design 3.
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
StarBuzz Coffee Recipe Boil some water Brew coffee in boiling water Pour coffee in cup Add sugar and milk Tea Recipe Boil some water Steep tea in boiling.
Five Minute Design Patterns Doug Marttila Forest and the Trees May 30, 2009 Template Factory Singleton Iterator Adapter Façade Observer Command Strategy.
An object's behavior depends on its current state. Operations have large, multipart conditional statements that depend on the object's state.
Structural Patterns C h a p t e r 4 – P a g e 55 StructuralPatterns Design patterns that describe how classes and objects can be combined to form larger.
Software Design and Architecture Muhammad Nasir Structural Design Patterns
Design Patterns CSCE 315 – Programming Studio Spring 2013.
Examples (D. Schmidt et al)
Facade Pattern Jim Fawcett CSE776 – Design Patterns Summer 2010
Design Patterns: MORE Examples
Describe ways to assemble objects to implement a new functionality
Software Design Patterns
Structural Patterns Structural patterns control the relationships between large portions of your applications. Structural patterns affect applications.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University
Introduction to Design Patterns
Facade Pattern Jim Fawcett CSE776 – Design Patterns Summer 2010
object oriented Principles of software design
Decorator Design Pattern
Design Patterns Satya Puvvada Satya Puvvada.
Object Oriented Design Patterns - Structural Patterns
Decorator Pattern Richard Gesick.
Structural Patterns: Adapter and Bridge
Software Design Lecture 10.
Presentation transcript:

Design Patterns Structural Patterns

Adapter Convert the interface of a class into another interface clients expect Adapter lets classes work together that couldn't otherwise because of incompatible interfaces Use the Adapter pattern when: –you want to use an existing class and its interface does not match the one you need –you need to use several existing subclasses, but it's impractical to adapt their interface by subclassing everyone. An object adapter can adapt the interface of its parent class Convert the interface of a class into another interface clients expect Adapter lets classes work together that couldn't otherwise because of incompatible interfaces Use the Adapter pattern when: –you want to use an existing class and its interface does not match the one you need –you need to use several existing subclasses, but it's impractical to adapt their interface by subclassing everyone. An object adapter can adapt the interface of its parent class

Adapter

Bridge Decouple an abstraction from its implementation so that the two can vary independently Use the Bridge pattern when: –you want run-time binding of the implementation –you want to share an implementation among multiple objects Decouple an abstraction from its implementation so that the two can vary independently Use the Bridge pattern when: –you want run-time binding of the implementation –you want to share an implementation among multiple objects

Bridge

Composite Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly Use this pattern whenever you have "composites that contain components, each of which could be a composite". Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly Use this pattern whenever you have "composites that contain components, each of which could be a composite".

Composite

Decorator Attach additional responsibilities to an object dynamically Decorators provide a flexible alternative to subclassing for extending functionality Attach additional responsibilities to an object dynamically Decorators provide a flexible alternative to subclassing for extending functionality

Problems Several classes with a similar operation (method), but different behavior. We want to use many combinations of these behaviors Several classes with a similar operation (method), but different behavior. We want to use many combinations of these behaviors

Example - Automated Hospital People come to the reception with problems They describe their problems A special doctoRobot is created that is specialized to treat their special situations. People come to the reception with problems They describe their problems A special doctoRobot is created that is specialized to treat their special situations.

Automated Hospital - Solution 1

Problems with solution-1 Sometimes we don’t have multiple inheritance. Even if we have, if is problematic, and bad design. 2 n possible classes to create before compilation. Sometimes we don’t have multiple inheritance. Even if we have, if is problematic, and bad design. 2 n possible classes to create before compilation.

A Better idea: Use Decorator

Decorator in our case

Code Example Widget* aWidget = new BorderDecorator( new HorScrollDecorator( new VerScrollDecorator( new TextWidget( 80, 24 )))); aWidget->draw(); Stream* aStream = new CompressingStream( new ASCII7Stream( new FileStream( "fileName.dat" ))); aStream->putString( "Hello world" ); Widget* aWidget = new BorderDecorator( new HorScrollDecorator( new VerScrollDecorator( new TextWidget( 80, 24 )))); aWidget->draw(); Stream* aStream = new CompressingStream( new ASCII7Stream( new FileStream( "fileName.dat" ))); aStream->putString( "Hello world" );

Benefits Flexible Don’t have to foresee all combinations Little objects Possible problems Performance Decorators are not necessarily always cummutative (surgeon and Anastasiolic)

Facade Provide a unified interface to a set of interfaces in a subsystem Facade defines a higher-level interface that makes the subsystem easier to use Create a class that is the interface to the subsystem Clients interface with the Facade class to deal with the subsystem It hides the implementation of the subsystem from clients It promotes weak coupling between the subsystems and its clients It does not prevent clients from using subsystems class, should it? Provide a unified interface to a set of interfaces in a subsystem Facade defines a higher-level interface that makes the subsystem easier to use Create a class that is the interface to the subsystem Clients interface with the Facade class to deal with the subsystem It hides the implementation of the subsystem from clients It promotes weak coupling between the subsystems and its clients It does not prevent clients from using subsystems class, should it?

Facade

Flyweight Use sharing to support large numbers of fine-grained objects efficiently The pattern can be used when: –The program uses a large number of objects and –Storage cost are high because of the sheer quantity of objects and –The program does not use object identity (==) Use sharing to support large numbers of fine-grained objects efficiently The pattern can be used when: –The program uses a large number of objects and –Storage cost are high because of the sheer quantity of objects and –The program does not use object identity (==)

Flyweight

Proxy Provide a surrogate or placeholder for another object to control access to it. The proxy has the same interface as the original object Virtual Proxy: –Creates/accesses expensive objects on demand –You may wish to delay creating an expensive object until it is really accessed –It may be too expensive to keep entire state of the object in memory at one time Provide a surrogate or placeholder for another object to control access to it. The proxy has the same interface as the original object Virtual Proxy: –Creates/accesses expensive objects on demand –You may wish to delay creating an expensive object until it is really accessed –It may be too expensive to keep entire state of the object in memory at one time

Protection Proxy –Provides different objects different level of access to original object Cache Proxy (Server Proxy) –Multiple local clients can share results from expensive operations: remote accesses or long computations Firewall Proxy –Protect local clients from outside world Protection Proxy –Provides different objects different level of access to original object Cache Proxy (Server Proxy) –Multiple local clients can share results from expensive operations: remote accesses or long computations Firewall Proxy –Protect local clients from outside world

Proxy

Dynamics

Don ’ t bother to make a copy of something until you really need one: Be Lazy ?! Use someone else ’ s copy as long as you can get away with it. Don ’ t bother to make a copy of something until you really need one: Be Lazy ?! Use someone else ’ s copy as long as you can get away with it. Reference Counting Class String { … }; String s1 = “Hello”; String s2=s1; cout << s1; cout << s1 + s2; S2.convertToUpperCase();

Reference Counting Copying the string contents in every –Assignment, –Argument passing, and –Function returning value Can be both –Expensive, and –Unnecessary! Copying the string contents in every –Assignment, –Argument passing, and –Function returning value Can be both –Expensive, and –Unnecessary!

The basic String class class String { public: String(const char* value= “”); String(const String& rhs); String& operator=(const String& rhs); … private: char *date; }; class String { public: String(const char* value= “”); String(const String& rhs); String& operator=(const String& rhs); … private: char *date; };

The common implementation String& String::operator=(const String& rhs) { if(this == &rhs) return * this; delete [] data; data = new char[strlen(rhs.data) + 1]; strcpy(data,rhs.data); return *this; } String& String::operator=(const String& rhs) { if(this == &rhs) return * this; delete [] data; data = new char[strlen(rhs.data) + 1]; strcpy(data,rhs.data); return *this; }

Using the String class String a,b,c,d,e; a=b=c=d=e=“Hello” String a,b,c,d,e; a=b=c=d=e=“Hello” String A String B String E String C String D Hello\0

The Idea Behind Reference Counting String A String B String E String C String D Hello\0 5 Reference

Implement The Reference Counting class String{ private: struct StringRef{ int refCount; char *data; StringRef(const char *initValue); ~StringRef(); }; StringRef *value; public: String(const char* value= “”); String(const String& rhs); String& operator=(const String& rhs); … };

StringRef class implementation String::StringRef::StringRef(const char* initVal) : refCount(1) { data = new char[strlen(initVal) + 1]; strcpy(data,initVal); } String::StringRef::~StringRef() { delete []data; }

String class implementation String::String(const char *initVal) : value(new StringRef(initVal)) {} String::String(const String& rhs) : value(rhs.value) { ++value->refCount; } String::~String() { if(--value->refCount == 0) delete value; }

String& String::operator=(const String& rhs) { if (value == rhs.value) return *this; if (--vaule->refCount == 0) delete value; value = rhs.value; ++value->refCount; return *this; } String class implementation

Using the String class String s1(“More Effective c++”); String s2(“More Effective c++”); String s3=s2; String s4; S4=s3; s1 s2 s3 s4 More Effective c++ \0 3 StringRef More Effective c++ \0 1

Copy on Write Class String { … public: char operator[](int index) const; char& operator[](int index); … }; char String::operator[](int index) const { return value->data[index]; }

Copy on Write char& String::operator[](int index) { if(value->refCount > 1){ --value->refCount; value = new StringRef(value->data); } return value->data[index]; } … String s1; const String s2; … cout << s1 << s2; s1[5] = ‘x’;

Distinguishing Reads from Writes Reading a reference counting is cheap Writing require splitting off a new copy String s = “H. Simpson”; cout << s[5]; S[5] = ‘I’;

Distinguishing Reads from Writes via operator[] class String{ public: class CharProxy{ public: CharProxy(String& str,int index); CharProxy& operator=(const CharProxy& rhs); CharProxy& opeartor=(char c); operator char() const; private: String& theString; int charIndex; }; const CharProxy operator[](int index) const; CharProxy operator[](int index); … friend class CharProxy; private: struct StringRef{…}; StringRef *value; };

Distinguishing Reads from Writes via operator[] const String::CharProxy String::operator[](int index) const { return CharProxy(const_cast (*this),index); } String::CharProxy String::operator[](int index) { return CharProxy(*this,index); } String::CharProxy::CharProxy(String& str,int index) : theString(str),charIndex(index){} String::CharProxy::operator char() const { return theString.value->data[charIndex]; }

Distinguishing Reads from Writes via operator[] String::CharProxy& String::CharProxy::operator=(const CharProxy& rhs) { if(theString.value->reCount > 1) theString.value = new StringRef(theString.value->data); theString.value->data[charIndex] = rhs.theString.value->data[charIndex]; return *this; } String::CharProxy& String::CharProxy::operator=(char c) { if(theString.value->reCount > 1) theString.value = new StringRef(theString.value->data); theString.value->data[charIndex] = c; return *this; }

Using the proxy class String s1,s2; … cout << s1[5]; s1[5] = ‘x’; s1[3] = s2[8];