1 Edgar Gabriel COSC 3351 Software Design Design Patterns Creational Patterns Edgar Gabriel Spring 2008 COSC 3351 – Software Design Edgar Gabriel Object Oriented Software Design • Determine right granularity of objects • Define class interfaces and inheritance hierarchies • Establish key relationships • Design should be specific to solve a problem • …but general enough to be reusable • Experienced designer do not solve every problem from scratch – Reuse solutions that worked in the past – Leads to recurring patterns in many programs
25
Embed
COSC 3351 Software Design Design Patterns Creational …gabriel/courses/cosc3351_s08/SD_13_CreationalPatterns.pdfSoftware Design Design Patterns Creational Patterns Edgar Gabriel Spring
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
1
Edgar Gabriel
COSC 3351
Software Design
Design Patterns
Creational Patterns
Edgar Gabriel
Spring 2008
COSC 3351 – Software Design
Edgar Gabriel
Object Oriented Software Design
• Determine right granularity of objects
• Define class interfaces and inheritance hierarchies
• Establish key relationships
• Design should be specific to solve a problem
• …but general enough to be reusable
• Experienced designer do not solve every problem from
scratch
– Reuse solutions that worked in the past
– Leads to recurring patterns in many programs
2
COSC 3351 – Software Design
Edgar Gabriel
Design patterns
• A design pattern is a way of reusing abstract knowledge about a problem and its solution– Patterns are devices that allow programs to share knowledge about
their design
• A pattern is a description of the problem and the essence of its solution– Documenting patterns is one way to reuse and share the
information about how it is best to solve a specific design problem
• A pattern should be sufficiently abstract to be reused in different settings
• Patterns often rely on object characteristics such as inheritance and polymorphism
COSC 3351 – Software Design
Edgar Gabriel
History of Design Patterns
• Architect Christopher Alexander
– A Pattern Language (1977)
– A Timeless Way of Building (1979)
• “Gang of four”
• Erich Gamma
• Richard Helm
• Ralph Johnson
• John Vlissides
– Design Patterns: Elements of Reusable Object-
Oriented Software (1995)
• Many since
• Conferences, symposia, books
3
COSC 3351 – Software Design
Edgar Gabriel
Pattern elements
• Name
– A meaningful pattern identifier
• Problem description
• Solution description
– Not a concrete design but a template for a design solution that can be instantiated in different ways
• Consequences
– The results and trade-offs of applying the pattern
COSC 3351 – Software Design
Edgar Gabriel
Abstraction Levels
Patterns exist on different abstraction levels:
• basic building blocks (algorithms and components), provided by
language or by libraries
• e.g. hash tables, linked lists, sort algorithms, math
• e.g. inheritance and polymorphism, encapsulation
• design patterns: general design problems in particular context
concerning several classes
• e.g.GOF-design patterns
• architecture patterns: architecture decisions concerning the
whole system (or subsystem)
• Architectural styles discussed previously
4
COSC 3351 – Software Design
Edgar Gabriel
Classifying design patterns
• Purpose:
– Creational: concern the process of object creation
– Structural: composition of classes or objects
– Behavioral: characterize ways in which objects interact and distribute responsibility
• Scope:
– Class patterns: deal with relationships between classes and subclasses, i.e. inheritance
• Static, compile time
– Object patterns: can be changed at runtime, dynamically
COSC 3351 – Software Design
Edgar Gabriel
Purpose
Creational Structural Behavioral
Scope Class Factory Method Adaptor(class) Interpreter
Template Method
Object Abstract Factory Adaptor(object) Chain of
Responsibility
Builder Bridge Command
Prototype Composite Iterator
Singleton Decorator Mediator
Façade Observer
Flyweight State
Proxy Strategy
Visitor
Memento
5
COSC 3351 – Software Design
Edgar Gabriel
Specifying Object Interfaces
• An operation declared by an object specifies
– Operation name
– Objects taken as parameter
– Return value
-> operation signature
• Set of signatures defines the interface of an object
• An interface does not say anything about the
implementation
– Different objects having the same interface
– Association of the request to an object at runtime known as dynamic binding
COSC 3351 – Software Design
Edgar Gabriel
Specifying Object Interfaces
• Class vs. Interface inheritance
– Class inheritance defines an objects implementation in terms of another objects implementation
• Mechanism for code reuse
– Interface inheritance defines describes when an object can be used in place of another
• Subtyping
• In C++: inherit publicly from a class that has (pure) virtual functions
6
COSC 3351 – Software Design
Edgar Gabriel
Putting Reuse Mechanisms to Work
• Class Inheritance
– Reuse by subclassing
– White box reuse: internals of parents class often visible to subclasses
– Defined statically at compile time
• Composition
– Assembling objects in order to create more complex objects
– Black-box reuse: no internal details of objects visible
COSC 3351 – Software Design
Edgar Gabriel
Putting Reuse Mechanisms to Work (II)
• Parameterized types
– Often called generics or templates
– Define a type without specifying the types it uses
– Static, compile time procedure
• Delegation:
– Two objects involved in handling a request
• A receiving object delegates the operation to the delegate
• Instead of the subclass being a ‘superclass’ the subclass would have a ‘superclass’ object
7
COSC 3351 – Software Design
Edgar Gabriel
Delegation example
13
class I {
public:
virtual void f() = 0;
virtual void g() = 0;
} class A : public I {
public:
void f() { cout << "A: doing f()" << endl; }
void g() { cout << "A: doing g()" << endl; }
}
class C : public I {
public:
C() : i( new A() ) { }
virtual ~C() { delete i; }
void f() { i->f(); }
void g() { i->g(); }
}
int main() {
C* c = new C();
c->f();
c->g();
}
COSC 3351 – Software Design
Edgar Gabriel
An example: a maze game
Maze
+ AddRoom()
+RoomNo()
Room
+ Enter()
+ SetSide()
+ GetSide()
- RoomNo
Wall
+ Enter()
Door
+ Enter()
- isOpen
<<interface>>
MapSite
+ Enter()
8
COSC 3351 – Software Design
Edgar Gabriel
15
class MapSite {
public:
virtual void Enter() = 0;
}; class Room : public MapSite {
public:
Room (int RoomNo);
MapSite * GetSide(Direction) const;
void SetSide (Direction, MapSite*);
virtual void Enter();
private:
MapSite *_sides[4];
int _RoomNo;
}
class Wall : public MapSite {
public:
Wall();
}
class Door: public MapSite {
public:
Door (Room *=0, Room*=0 );
virtual void Enter();
Room * OtherSideFrom (Room *);
private:
Room *_room1, *_room2;
bool _isOpen;
}
COSC 3351 – Software Design
Edgar Gabriel
16
// This class represents a collection of rooms
class Maze {
public:
Maze();
void AddRoom (Romm *);
Room* RoomNo(int) const;
}; // The class MazeGame creates a Maze
Maze * MazeGame:: CreateMaze {
Maze* aMaze = new Maze;
Room* r1 = new Room( 1 );
Room* r2 = new Room( 2 );
Door* theDoor = new Door( r1, r2);
aMaze->addRoom( r1 );
aMaze->addRoom( r2 );
r1->setSide( North, new Wall );
r1->setSide( East, theDoor );
r1->setSide( South, new Wall );
r1->setSide( West, new Wall );
r2->setSide( North, new Wall );
r2->setSide( East, new Wall );
r2->setSide( South, new Wall );
r2->setSide( West, theDoor );
return aMaze;
}
9
COSC 3351 – Software Design
Edgar Gabriel
Problem with previous code
• Contains the explicit types of Room, Door etc.
– Difficult to reuse the room layout described by CreateMaze for other type of Doors, Walls etc.
class BombedMazeGame : public MazeGame {
public:
Maze* CreateMaze() {
Maze* aMaze = new Maze;
Room* r1 = new RoomWithABomb( 1 );
Room* r2 = new RoomWithABomb( 2 );
Door* theDoor = new Door( r1, r2);
aMaze->addRoom( r1 );
aMaze->addRoom( r2 );
r1->setSide( North, new BombedWall);
r1->setSide( East, theDoor );
…
COSC 3351 – Software Design
Edgar Gabriel
Abstract Factory
• Intent: Provide an interface for creating families of
related or dependent objects without specifying their
concrete classes
• Applicability: Use the Abstract Factory Pattern when
– A system should be independent of how its products are created, composed and represented
– A system should be configured with one of multiple families of products
– A family of related product objects is designed to be
used together, and you need to enforce this constraint
– You want to provide a class library of products, and you want to reveal just the interfaces, not their implementation
10
COSC 3351 – Software Design
Edgar Gabriel
Abstract Factory (II)
class MazeFactory {
public:
MazeFactory() {
virtual Maze* MakeMaze() const {return new Maze; }
virtual Wall* MakeWall() const {return new Wall; }
– Builder pattern focuses on constructing a complex object step by step
– Abstract Factory emphasis is on a family of product objects
– E.g. CreateMaze does not have anywhere the notion, that you are dealing with objects of type Room or Door.
19
COSC 3351 – Software Design
Edgar Gabriel
Formal Model
Director
ConcreteBuilder
<<interface>>
Builder
+BuildPart()
+BuildPart()
for all objects in structure{
builder->BuildPart();
}
Construct()
Product
COSC 3351 – Software Design
Edgar Gabriel
Builder• Participants:
– Builder: specifies an abstract interface for creating parts of a Product object
– Concrete Builder:
• constructs and assembles parts of the product by implementing the BuilderInterface
• Defines and keeps track of the representations it creates
• Provides an interface for retrieving the product
– Director: constructs an object using the Builder Interface
– Product:
• represents the complex object under construction
• define the process by which it is assembled.
20
COSC 3351 – Software Design
Edgar Gabriel
Builder
• Why no abstract class for the products?
– In the common case, the products produced by the concrete builder differ so greatly in their representation that there is little gain from giving different products a common parent class
COSC 3351 – Software Design
Edgar Gabriel
Another exampleclass CountingMazeBuilder: public MazeBuilder {
public:
virtual void BuildMaze();
virtual void BuildRoom (int room );
virtual void BuildDoor ( int room1, int room2 );
virtual Maze* GetMaze();
private:
int _doors, _rooms;
}
CoutingMazeBuilder:: CountingMazeBuilder () {
_rooms = _doors = 0;
}
void CountingMazeBuilder:: BuildRoom (int) {
_rooms++;
}
void CountingMazeBuilder:: BuildDoor(int, int ) {
_doors++;
}
21
COSC 3351 – Software Design
Edgar Gabriel
Prototype
• Intent: Specify the kinds of objects to create using a
prototypical instance and create new objects by
copying this prototype
• Applicability: use the prototype patterns when a system
should be independent of how its products are created,
composed and represented, and
– When the classes to instantiate are specified at runtime
– To avoid building a class hierarchy of factories which parallels the class hierarchy of products
– When instances of a class can have one of only a few different combinations