You are on page 1of 58

91.204.

201
Computing IV
Introduction to Design Pattern
Xinwen Fu

Useful References

Design Pattern

Major reference of various design pattern for


this class

Youtube videos on UML

Visual Paradigm for drawing UML

Community edition is free

By Dr. Xinwen Fu

CS@UML

Outline
Introduction to Pattern
Gang of Four Design Pattern
Adapter Pattern
Introduction to UML

By Dr. Xinwen Fu

CS@UML

What is a Pattern?

Current use comes from the work of the architect


Christopher Alexander

Alexander studied ways to improve the process of


designing buildings and urban areas

Each pattern is a three-part rule, which expresses a


relation between

Hence, the common definition of a pattern

a certain context, a problem and a solution.


A solution to a problem in a context.

Patterns can be applied to many different areas of


human endeavor, including software development
By Dr. Xinwen Fu

CS@UML

Pattern of Porches

Classical House Styles

American Colonial Styles

Victorian House Styles

CS@UML

Spanish and Mediterranean


By Dr. Xinwen Fu

Why Patterns?

"Designing object-oriented software is hard and


designing reusable object-oriented software is even
harder." - Erich Gamma

Experienced designers reuse solutions that have


worked in the past

Well-structured object-oriented systems have


recurring patterns of classes and objects

Knowledge of the patterns that have worked in the


past allows a designer to be more productive and the
resulting designs to be more flexible and reusable
By Dr. Xinwen Fu

CS@UML

Software Patterns History

1987 - Cunningham and Beck used Alexanders ideas to


develop a small pattern language for Smalltalk

1990 - The Gang of Four (Gamma, Helm, Johnson and


Vlissides) begin work compiling a catalog of design patterns

1991 - Bruce Anderson gives first Patterns Workshop at


OOPSLA

1993 - Kent Beck and Grady Booch sponsor the first meeting
of what is now known as the Hillside Group

1994 - First Pattern Languages of Programs (PLoP) conference

1995 - The Gang of Four (GoF) publish the Design Patterns


book

By Dr. Xinwen Fu

CS@UML

Types of Software Patterns

Riehle and Zullighoven in Understanding and Using


Patterns in Software Development mention three types of
software patterns

Conceptual Pattern

Design Pattern

Pattern whose form is described by means of terms and concepts


from the application domain

Pattern whose form is described by means of software design


constructs, such as objects, classes, inheritance and aggregation

Programming Pattern (Programming Idiom)

Pattern whose form is described by means of programming


language constructs
By Dr. Xinwen Fu

CS@UML

Design Pattern: Levels of


Abstraction

Complex design for an entire application


or subsystem - Conceptual Pattern

Solution to a general design problem in a


particular context - Design Pattern

Simple reusable design class such as a


linked list, hash table, etc. - Programming
Pattern
By Dr. Xinwen Fu

CS@UML

Outline
Introduction to Pattern
Gang of Four Design Pattern
Adapter Pattern
Introduction to UML

By Dr. Xinwen Fu

CS@UML

10

GoF Design Patterns

The GoF design patterns are in the middle of


these levels of abstraction

A design pattern names, abstracts, and


identifies key aspects of a common design
structure that makes it useful for creating a
reusable object-oriented design.

The GoF design patterns are descriptions of


communicating objects and classes that are
customized to solve a general design problem
in a particular context.
By Dr. Xinwen Fu

CS@UML

11

GoF Classification Of Design


Patterns

Purpose - what a pattern does

Creational Patterns

Structural Patterns

Concern the process of object creation

Deal with the composition of classes and objects

Behavioral Patterns

Deal with the interaction of classes and objects


By Dr. Xinwen Fu

CS@UML

12

Purpose

Design Pattern

Aspect(s) That Can Vary

Creational

Abstract Factory (99)

families of product objects

Builder (110)

how a composite object gets created

Factory Method (121)

subclass of object that is instantiated

Prototype (133)

class of object that is instantiated

Singleton (144)

the sole instance of a class

Adapter (157)

interface to an object

Bridge (171)

implementation of an object

Composite (183)

structure and composition of an object

Decorator (196)

responsibilities of an object without subclassing

Facade (208)

interface to a subsystem

Flyweight (218)

storage costs of objects

Proxy (233)

how an object is accessed; its location

Chain of Responsibility
(251)

object that can fulfill a request

Command (263)

when and how a request is fulfilled

Interpreter (274)

grammar and interpretation of a language

Iterator (289)

how an aggregate's elements are accessed, traversed

Mediator (305)

how and which objects interact with each other

Memento (316)

what private information is stored outside an object, and when

Observer (326)

number of objects that depend on another object; how the dependent


objects stay up to date

State (338)

states of an object

Strategy (349)

an algorithm

Template Method (360)

steps of an algorithm

Structural

Behavioral

CS@UML Visitor (366)

operations that can be applied to object(s) without changing their class(es)

Online Materials

Design Patterns

Erich Gamma, Richard Helm, Ralph


Johnson, and John Vlissides, Design
Patterns: Elements of Reusable ObjectOriented Software, Addison Wesley.
October 1994.

By Dr. Xinwen Fu

CS@UML

14

Iterator

By Dr. Xinwen Fu

CS@UML

15

Common Pattern: The Big Ball


of Mud
Shantytowns are usually built

from common, inexpensive


materials and simple tools.
Shantytowns built using
relatively unskilled labor.

Even though the labor force is


"unskilled" in the customary
sense, the construction and
maintenance of this sort of
housing can be quite labor
intensive.

There is little specialization.


Each housing unit is
constructed and maintained
primarily by its inhabitants
By Dr. Xinwen Fu

CS@UML

16

Common Pattern: Spaghetti


Code

Overgrown, tangled,
haphazard spaghetti
code is hard to
comprehend, repair,
or extend, and tends
to grow even worse
if it is not somehow
brought under
control.

By Dr. Xinwen Fu

CS@UML

17

Outline
Introduction to Pattern
Gang of Four Design Pattern
Adapter Pattern
Introduction to UML

By Dr. Xinwen Fu

CS@UML

18

C++ Example
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.

#include <iostream.h>
using namespace std;
typedef int Coordinate;
typedef int Dimension;
// Desired interface (Target)
class Rectangle {
public:
virtual void draw() = 0;
};
// Legacy component (Adaptee)
class LegacyRectangle {
public:
LegacyRectangle(int x1, int y1, int x2, int y2) {
x1_ = x1;
y1_ = y1;
x2_ = x2;
y2_ = y2;
cout << "LegacyRectangle: create. (" << x1_ << "," << y1_ << ") => ("
<< x2_ << "," << y2_ << ")" << endl;
}
By Dr. Xinwen Fu
19

CS@UML

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.

void oldDraw() {
cout << "LegacyRectangle: oldDraw. (" << x1_ << "," << y1_ <<
") => (" << x2_ << "," << y2_ << ")" << endl;
}
private:
int x1_, y1_, x2_, y2_;
};
// Adapter wrapper
class RectangleAdapter: public Rectangle, private LegacyRectangle {
public:
RectangleAdapter(int x, int y, int w, int h):
LegacyRectangle(x, y, x + w, y + h) {
cout << "RectangleAdapter: create. (" << x << "," << y <&lt;
"), width = " << w << ", height = " << h << endl;
}
virtual void draw() {
cout << "RectangleAdapter: draw." << endl;
oldDraw();
}
};

int main() {
22.
Rectangle *r = new RectangleAdapter(120, 200, 60, 40);
23.
r->draw();
By Dr. Xinwen Fu
24.
}
CS@UML
21.

20

Understanding the Start of an


Object's Lifetime
1.
2.
3.
4.
5.

6.
7.
8.
9.

#include <iostream>
class Foo {
public:
Foo() { std::cout << "Foo's constructor" << std::endl; }
};
class Bar : public Foo {
public:
Bar() { std::cout << "Bar's constructor" << std::endl; }
};

int main() {
11.
// a lovely elephant ;)
12.
Bar bar;
13. }
10.

By Dr. Xinwen Fu

CS@UML

21

Interface classes

An interface class is a class that has no members


variables, and where all of the functions are pure
virtual!

In other words, the class is purely a definition,


and has no actual implementation.

Interfaces are useful when you want to define the


functionality that derived classes must
implement, but leave the details of how the
derived class implements that functionality
entirely up to the derived class.

22

CS@UML

Example of Interface Class


1.
2.
3.
4.

class IErrorLog
{
virtual bool OpenLog(const char *strFilename) = 0;
virtual bool CloseLog() = 0;

5.

virtual bool WriteError(const char *strErrorMessage) = 0;

6.
7.

};

23

CS@UML

The Adapter Pattern

Intent

Convert the interface of a class into another interface


clients expect
Adapter lets classes work together that couldn't otherwise
because of incompatible interfaces

Also Known As Wrapper


Motivation

Sometimes a toolkit or class library cannot be used because


its interface is incompatible with the interface required by
an application
We cannot change the library interface, since we may not
have its source code
Even if we did have the source code, we probably should
not change the library for each domain-specific application
By Dr. Xinwen Fu

CS@UML

24

Use of Adapter pattern

Applicability: Use the Adapter pattern when

You want to use an existing class, and its interface does


not match the one you need
You want to create a reusable class that cooperates with
unrelated classes with incompatible interfaces

Implementation Issues

How much adapting should be done?

Simple interface conversion that just changes operation


names and order of arguments
Totally different set of operations

Does the adapter provide two-way transparency?

A two-way adapter supports both the Target and the


Adaptee interface. It allows an adapted object (Adapter) to
appear as an Adaptee object or a Target object
By Dr. Xinwen Fu

CS@UML

25

Class Adapter

A class adapter uses multiple inheritance to adapt


one interface to another

By Dr. Xinwen Fu

CS@UML

26

Object Adapter

An object adapter relies on object composition

By Dr. Xinwen Fu

CS@UML

27

Outline
Introduction to Pattern
Gang of Four Design Pattern
Adapter Pattern
Introduction to UML

By Dr. Xinwen Fu

CS@UML

28

Objectives of UML

UML (Unified Modeling Language) is the result of


an effort to simplify and consolidate the large
number of OO development methods and
notations
UML is a general purpose notation that is used to
visualize,
specify,
construct, and
document
the artifacts of a software system

29

CS@UML

A Class in UML

Class name: Must have, other two


Visibility
are optional
Mark
type
Attribute format

name : attribute type = default value

Operation (method) format

Name(paramater list): return type

Public

Protected

Private

Package

Class name
Attribute
Operator
30

CS@UML

Object Diagram
object name : class

31

CS@UML

Class Relationships in UML

Inheritance

Association

An inheritance link: triangle pointing to superclass


-Role1
*

-Role2
0..1

A relationship between instances of the two classes


Two ends: an end can have a role name to clarify the
nature of the association
The number of possible instances of the class
associated with a a single instance at the other end

Dependency

One depends on another if changes in the other could


possibly force changes in the first
32

CS@UML

By Dr. Xinwen Fu

CS@UML

33

Sensor

Generalization
CalibratingSensor

An

is-a relationship
Abstract class in italic font

+currentValue()
+calibrate()

HistoricalSensor

WindDirectionSensor
+currentDirection()

-highestValue
-lowestVale
+resetHighest()
+resetLowest()

TrendSensor
-trend

TemperatureSensor
CS@UML

HumiditySensor

WindspeedSensor

-humidity

-speed

+currentHumidity()

+currentSpeed()

Barometer

-temp

-pressure

+currentTemp()

+currentPressure()

34

UML 2.0: Interface

35

CS@UML

Association

An association represents a family of links

Structural relationship between peer classes (or objects)

Association can have a name and direction (indicated by an open


arrowhead), or be bi-directional (solid line)

Role names for each end of the association

Multiplicity of the relationship

36

CS@UML

Examples of Association

Bi-directional association

Uni-directional association

37

CS@UML

Complicated Association:
Aggregation and Composition

Aggregation is a shared
containment. Many other
classes may have the same type
of aggregate. e.g., string, list

Pointers to dependent class


instances

Composition is aggregates that


can not stand by themselves
(e.g., foot, arm, etc)

Represent real-world whole-part


relationships
Instance of dependent class

38

CS@UML

Dependency

A weaker form of bond which indicates that one class depends


on another because it uses it at some point in time.

A class depends on another if the independent class is a parameter


variable or local variable of a method of the dependent class.

This is different from an association, where an attribute of the


dependent class is an instance of the independent class.

In an e-commerce application, a Cart class depends on a


Product class because the Cart class uses the Product class as a
parameter for an add operation.

In a class diagram, a dependency relationship points from the Cart


class to the Product class.

The Cart class is the client, and the Product class is the supplier

Product
39

CS@UML

Dependency Example

Here is a simple rule for when a dependency occurs. If the code for one class contains the
name of another class in the diagram, and no other connection exists in the diagram between
them then there should be a dashed dependency arrow from the first to the second class

5.

class A
{
public:
B returns_a_B();
void has_a_B_argument(B);
void has_a_B_in_its_implementation();
};

6.

A::void has_a_B_in_its_implementation(){ B b; }

1.
2.
3.
4.

40

CS@UML

Which Relation is Right?

Association is "use a" or "use a" relationship

Aggregation is a variant of the "has a" association


relationship

Composition is a stronger variant of the "owns a"


association relationship;

composition is more specific than aggregation.

The Generalization relationship ("is a") indicates that one of


the two related classes (the subclass) is considered to be a
specialized form of the other (the super type)

aggregation is more specific than association.

superclass is considered as 'Generalization' of subclass.

Dependency is a weaker form of bond

not an instance in the dependent class


41

CS@UML

Visual Paradigm for UML 10.1


Community Edition

Visual Paradigm for UML is a UML


modeling software that supports UML,
SysML, ERD, BPMN, DFD, ArchiMate, etc.
UML diagrams, use case, SysML
requirements, enterprise architecture,
code engineering and database design are
supported for effective system analysis
and design

Community Edition is free

Youtube videos on UML


By Dr. Xinwen Fu

CS@UML

42

Visual Paradigm

Only problem is e

By Dr. Xinwen Fu

CS@UML

43

Liability of Free Version

Exported image of a diagram has watermarks

By Dr. Xinwen Fu

CS@UML

44

Watermarked Diagram

Solution: alt + prtscr for screenshots

By Dr. Xinwen Fu

CS@UML

45

Popular Design Patterns

The Big Ball of Mud (lol) Adaptor


Faade
Spaghetti code
MVC
Factory
Singleton
Abstract Factory
Observer (event
Composite
distribution)
Template
Decorator
service-locator
Strategy
Repository pattern
Iterator
Interpreter
Builder
By Dr. Xinwen Fu

CS@UML

46

Backup

By Dr. Xinwen Fu

CS@UML

47

Reference
1.
2.
3.
4.
5.
6.

Java Design Patterns At a Glance, November 30, 2009


Allen Holub, Allen Holub's UML Quick Reference, Version
2.1.2, 2007/08/10
Laurent Grgoire, UML Quick Reference Card, 2001
UML Resource Page, 2009
Randy Miller, Practical UML: A Hands-On Introduction for
Developers, 2009
Design Patterns (with C++, C#, Java, PHP, and Delphi
examples), 2011

By Dr. Xinwen Fu

CS@UML

48

Types of Software Patterns

Analysis: Conceptual models

Design: A solution to a problem in a context


Organizational: Recurring structures of relationship, usually
in a professional organization, that help the organization
achieve its goals
Process: Common template for software development
process
Project Planning: Part of project management

Capture an abstraction of a situation that can often be


encountered in modeling

Relates to the use of schedules such as Gantt charts to plan


and subsequently report progress within the project
environment

Configuration Management: a field of management

Focuses on establishing and maintaining consistency of a


system's or product's performance and its functional and
physical attributes with its requirements, design, and
operational information throughout its life
By Dr. Xinwen Fu

CS@UML

49

By Dr. Xinwen Fu

CS@UML

50

UML Part II
Introduction to UML
Use Case Diagrams
Class Diagrams
Modeling Behavior and Sequence
Diagrams

51

CS@UML

Objectives of UML

UML is the result of an effort to


simplify and consolidate the large
number of OO development
methods and notations
UML is a general purpose notation
that is used to
visualize,
specify,
construct, and
document
the artifacts of a software system

52

CS@UML

Why do We Need Virtual


functions?
1.
2.

3.
4.
5.

class Base {
protected:

public:
const char* GetName() { return "Base"; }
};

6.
7.
8.
9.
10.

class Derived: public Base {


public:
const char* GetName() { return "Derived"; }
};

11.
12.
13.
14.
15.
16.

int main() {
Derived cDerived;
Base &rBase = cDerived;
cout << "rBase is a " << rBase.GetName() << endl;
}

53

CS@UML

Virtual functions
1.
2.

class Base {
protected:

3.
4.
5.
6.

public:
virtual const char* GetName() { return "Base"; }
};

7.
8.
9.
10.
11.

class Derived: public Base {


public:
virtual const char* GetName() { return "Derived"; }
};

12.
13.
14.
15.
16.

int main() {
Derived cDerived;
Base &rBase = &cDerived;
cout << "rBase is a " << rBase.GetName() << endl;

17.

return 0;

18.
19.

}
54

CS@UML

Pure virtual function (abstract


function)
A pure virtual function (or abstract function) that has no body at all

When we add a pure virtual function to our class, we are effectively


saying, it is up to the derived classes to implement this function.

1.

class Base {
public:
// a normal non-virtual function
const char* SayHi() { return "Hi"; }

2.
3.
4.
5.

// a normal virtual function


virtual const char* GetName() { return "Base"; }

6.
7.
8.

virtual int GetValue() = 0; // a pure virtual function

9.
10.

};

55

CS@UML

Consequences of Using Pure Virtual


Function

First, any class with one or more pure


virtual functions becomes an abstract
base class

which means that it can not be instantiated!

Second, any derived class must define a


body for this function, or that derived
class will be considered an abstract base
class as well
56

CS@UML

Interface classes

An interface class is a class that has no members


variables, and where all of the functions are pure
virtual!

In other words, the class is purely a definition, and


has no actual implementation.

Interfaces are useful when you want to define the


functionality that derived classes must implement,
but leave the details of how the derived class
implements that functionality entirely up to the
derived class.
57

CS@UML

Example of Interface Class


1.
2.
3.
4.

class IErrorLog
{
virtual bool OpenLog(const char *strFilename) = 0;
virtual bool CloseLog() = 0;

5.

virtual bool WriteError(const char *strErrorMessage) = 0;

6.
7.

};

58

CS@UML

You might also like