0% found this document useful (0 votes)
11 views41 pages

Design Patterns in Software Engineering

The document outlines key design patterns in software engineering, focusing on their usefulness and categories, including Composite, Facade, Adapter, and Bridge patterns. It discusses techniques for identifying objects in system development and emphasizes the importance of design patterns for creating reusable and flexible designs. The document also covers various concepts related to object-oriented design, including delegation, inheritance, and the differences between adapter and bridge patterns.

Uploaded by

Juan Aguayo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views41 pages

Design Patterns in Software Engineering

The document outlines key design patterns in software engineering, focusing on their usefulness and categories, including Composite, Facade, Adapter, and Bridge patterns. It discusses techniques for identifying objects in system development and emphasizes the importance of design patterns for creating reusable and flexible designs. The document also covers various concepts related to object-oriented design, including delegation, inheritance, and the differences between adapter and bridge patterns.

Uploaded by

Juan Aguayo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

TUM

Design Patterns

Bernd Brügge
2
Technische Universität München
Lehrstuhl für Angewandte Softwaretechnik

22 June 1999

Bernd Bruegge Component Based Software Engineering 1


Outline of the Lecture

v Design Patterns
w Usefulness of design patterns
w Design Pattern Categories
v Patterns covered in this Lecture
w Composite: Model dynamic aggregates
w Facade: Interfacing to subsystems
w Adapter: Interfacing to existing systems (legacy systems)
w Bridge: Interfacing to existing and future systems

Bernd Bruegge Component Based Software Engineering 2


Finding Objects

v The hardest parts in system development:


w Identifying objects
w Decomposing a system into objects
v Requirements Analysis focuses on application domain:
w Object identification
v System Design addresses both, application and
implementation domain:
w Subsystem Identification
v Object Design focuses on implementation domain:
w More object identification

Bernd Bruegge Component Based Software Engineering 3


Techniques for Finding Objects

v Requirements Analysis
w Start with Use Cases. Identify participating objects
w Textual analysis of flow of events (find nouns, verbs, ...)
w Extract application domain objects by interviewing client
(application domain knowledge)
w Find objects by using general knowledge
v System Design
w Subsystem decomposition
w Try to identify layers and partitions
v Object Design
w Find additional objects by applying implementation domain
knowledge

Bernd Bruegge Component Based Software Engineering 4


Another Source for Finding Objects : Design Patterns

v Observation [Gamma et al 95]:


w Strict modeling of the real world leads to a system that reflects
today’s realities but not necessarily tomorrow’s.
v There is a need for reusable and flexible designs
v Design knowledge complements application domain
knowledge and implementation domain knowledge.
v What are Design Patterns?
w A design pattern describes a problem which occurs over and over
again in our environment, and then describes the core of the solution
to that problem, in such a way that you can use the this solution a
million times over, without ever doing it the same twice

Bernd Bruegge Component Based Software Engineering 5


Design Patterns Notation

v Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides,


Design Patterns: Elements of Reusable Object-Oriented
Software, Addison Wesley, 1995
v Based on OMT Notation
v Notational issues
w Attributes come after the Operations
w Associations are called acquaintances
w Multiplicities are shown as solid circles
w Inheritance shown as triangle
w Dashed line : Instantiation Assocation (Class can instantiate objects
of associated class) (In UML it denotes a dependency
w UML Note is called Dogear box (connected by dashed line to class
operation): Pseudo-code implementation of operation

Bernd Bruegge Component Based Software Engineering 6


Review: Modeling Typical Aggregations

Fixed Structure: Car

Doors Wheels Battery Engine

Organization Chart (variable aggregate):

University School Department

Dynamic tree (recursive aggregate):


Program

Block

Compound Simple
Statement Statement

Bernd Bruegge Component Based Software Engineering 7


Review: Modeling Typical Aggregations

Fixed Structure: Car

Doors Wheels Battery Engine

Organization Chart (variable aggregate):

University School Department

Composite
Program
Pattern
Dynamic tree (recursive aggregate):

Block

Compound Simple
Statement Statement

Bernd Bruegge Component Based Software Engineering 8


Composite Pattern
v Composes objects into tree structures to represent part-whole
hierarchies with arbitrary depth and width.
v The Composite Pattern lets client treat individual objects and
compositions of these objects uniformly

Client Component

Composite
Leaf
Children
Operation()
Operation() AddComponent
RemoveComponent()
GetChild()
Bernd Bruegge Component Based Software Engineering 9
Graphic Applications use Composite Patterns
• The Graphic Class represents both primitives (Line,
Circle) and their containers (Picture)

Client Graphic

Picture
Line Circle
Children
Draw()
Draw() Draw() Add(Graphic g)
RemoveGraphic)
GetChild(int)

Bernd Bruegge Component Based Software Engineering 10


Modeling Software Development with Composite
Patterns

v Software Lifecycle:
w Definition: The software lifecycle consists of a set of development
activities which are either other actitivies or collection of tasks
w Composite: Activity (The software lifecycle consists of activities
which consist of activities, which consist of activities, which....)
w Leaf node: Task
v Software System:
w Definition: A software system consists of subsystems which are
either other subsystems or collection of classes
w Composite: Subsystem (A software system consists of subsystems
which consists of subsystems , which consists of subsystems,
which...)
w Leaf node: Class

Bernd Bruegge Component Based Software Engineering 11


Modeling the Software Lifecycle with a Composite
Pattern

Software
Manager
Lifecycle

Task
Children
Activity

Bernd Bruegge Component Based Software Engineering 12


Modeling a Software System with a Composite
Pattern

Software
Developer System

Class
Children
Subsystem

Bernd Bruegge Component Based Software Engineering 13


Ideal Structure of a Subsystem: Façade, Adapter, Bridge

v A subsystem consists of
w an interface object
w a set of application domain objects (entity objects)
modeling real entities or existing systems
u Some of the application domain objects are interfaces to existing
systems
w one or more control objects
v Realization of Interface Object: Facade
w Provides the interface to the subsystem
v Interface to existing systems: Adapter or Bridge
w Provides the interface to existing system (legacy system)
w The existing system is not necessarily object-oriented!
Bernd Bruegge Component Based Software Engineering 14
Facade Pattern

v Provides a unified interface to a set of objects in a subsystem.


v A facade defines a higher-level interface that makes the
subsystem easier to use (i.e. it abstracts out the gory details)
v Facades allow us to provide a closed architecture

Bernd Bruegge Component Based Software Engineering 15


Open vs Closed Architecture
v Open architecture:
VIP Subsystem
w Any client can see into the
vehicle subsystem and call on
any component or class operation
at will.
v Why is this good?
w Efficiency Vehicle Subsystem
v Why is this bad?
w Can’t expect the caller to Seat
understand how the subsystem
works or the complex Card
relationships within the
subsystem. AIM SA/RT
w We can be assured that the
subsystem will be misused,
leading to non-portable code

Bernd Bruegge Component Based Software Engineering 16


Realizing a Closed Architecture with a Facade
VIP Subsystem
v The subsystem decides
exactly how it is accessed.
v No need to worry about
misuse by callers
v If a façade is used the
subsystem can be used in an Vehicle Subsystem API
early integration test
w We need to write only a driver
Seat Card

AIM SA/RT

Bernd Bruegge Component Based Software Engineering 17


Realizing a Compiler with a Facade pattern
Compiler

Compiler

compile(s)

CodeGenerator Lexer

create() getToken()

Optimizer Parser

create() generateParseTree()

ParseNode

create()

Bernd Bruegge Component Based Software Engineering 18


UML Notation for subsystems: Package
v Package = Collection of classes that are grouped together
v Packages are often used to model subsystems
v Notation:
w A box with a tab.
w The tab contains the name of the package
Compiler Compiler
Compiler

compile(s)

CodeGenerator Lexer

create() getToken()

Optimizer Parser

create() generateParseTree()

ParseNode

create()

v In Together-J, every class is assigned to a default package


w When you create a class, the class is assigned to the default package
directly containing the class diagram.
w You can create other packages, but cannot delete the default package
Bernd Bruegge Component Based Software Engineering 19
Class Adapter Pattern
(based on Multiple Inheritance)

Target Adaptee (Legacy Object)


Client
Request() ExistingRequest()

Adapter

Request()

Bernd Bruegge Component Based Software Engineering 20


Some Additional Definitions

v Before we go to the next pattern let’s review


the goal and some terms

Bernd Bruegge Component Based Software Engineering 21


Reuse
v Main goal:
w Reuse knowledge from previous experience to current problem
w Reuse functionality already available
v Composition (also called Black Box Reuse)
w New functionality is obtained by aggregation
w The new object with more functionality is an aggregation
of existing components
v Inheritance (also called White-box Reuse)
w New functionality is obtained by inheritance.
v Three ways to get new functionality:
u Implementation inheritance

u Interface inheritance

u Delegation

Bernd Bruegge Component Based Software Engineering 22


Implementation Inheritance vs Interface Inheritance

v Implementation inheritance
w Also called class inheritance
w Goal: Extend an applications’ functionality by reusing
functionality in parent class
w Inherit from an existing class with some or all operations
already implemented

v Interface inheritance
w Also called subtyping
w Inherit from an abstract class with all operations
specified, but not yet implemented

Bernd Bruegge Component Based Software Engineering 23


Implementation Inheritance
v A very similar class is already implemented that does almost
the same as the desired class implementation.

v Example: I have a List List


Add ()
class, I need a Stack Remove()
class. How about “Already
subclassing the Stack implemented”
class from the List class
and providing three Stack
Push ()
methods, Push() and Pop()
Pop(), Top()? Top()

v Problem with implementation inheritance:


Some of the inherited operations might exhibit unwanted
behavior. What happens if the Stack user calls Remove()
instead of Pop()?
Bernd Bruegge Component Based Software Engineering 24
Delegation

v Delegation is a way of making composition (for example


aggregation) as powerful for reuse as inheritance
v In Delegation two objects are involved in handling a request
w A receiving object delegates operations to its delegate.
w The developer can make sure that the receiving object does not allow
the client to misuse the delegate object

calls Delegates to Delegate


Client Receiver

Bernd Bruegge Component Based Software Engineering 25


Delegation or Inheritance?

v Delegation
w Pro:
u Flexibility: Any object can be replaced at run time by another one (as
long as it has the same type)
w Con:
u Inefficiency: Objects are encapsulated.
v Inheritance
w Pro:
u Straightforward to use
u Supported by many programming languages
u Easy to implement new functionality
w Con:
u Inheritance exposes a subclass to the details of its parent class
u Any change in the parent class implementation forces the subclass to
change (which requires recompilation of both)

Bernd Bruegge Component Based Software Engineering 26


Delegation instead of Inheritance

v Delegation: Catching an operation and sending it to another


object.

List

+Add() Stack List


+Remove()

Remove()
+Push() Add()
Stack +Pop()
+Top()
+Push()
+Pop()
+Top()

Bernd Bruegge Component Based Software Engineering 27


Many design patterns use a
combination of inheritance and
delegation

Bernd Bruegge Component Based Software Engineering 28


Adapter Pattern

v “Convert the interface of a class into another interface clients


expect. Adapter lets classes work together that couldn’t
otherwise because of incompatible interfaces
v Used to provide a new interface to existing legacy components
(Interface engineering, reengineering).
v Also known as a wrapper
v Two adapter patterns:
w Class adapter:
u Uses multiple inheritance to adapt one interface to another
w Object adapter:
u Uses single inheritance and delegation
v We will mostly use object adapters and call them simply
adapters
Bernd Bruegge Component Based Software Engineering 29
Adapter pattern
Target Adaptee
Client
Request() ExistingRequest()

adaptee

Adapter

Request()
v Delegation is used to
bind an Adapter and an Adaptee
v Interface inheritance is use to specify the interface of the
Adapter class.
v Target and Adaptee (usually called legacy system) pre-exist
the Adapter.
v Target may be realized as an interface in Java.

Bernd Bruegge Component Based Software Engineering 30


Adapter pattern example
Enumeration
RegisteredServices
Client numServices();
hasMoreElements()
getService(int num);
nextElement()

adaptee

ServicesEnumeration
hasMoreElements()
public class ServicesEnumeration nextElement()
implements Enumeration {
public boolean hasMoreElements() {
return [Link] <= [Link]();
}
public Object nextElement() {
if (![Link]()) {
throw new NoSuchElementException();
}
return [Link]([Link]++);
}
Bernd Bruegge Component Based Software Engineering 31
Bridge Pattern

v Usea bridge to “decouple an abstraction from its


implementation so that the two can vary
independently”. (From [Gamma et al 1995])

v Also know as a Handle/Body pattern.

v Allows different implementations of an interface to


be decided upon dynamically.

Bernd Bruegge Component Based Software Engineering 32


Using a Bridge
v The bridge pattern is used to provide multiple
implementations under the same interface.
v Examples: Interface to a component that is incomplete, not yet
known or unavailable during testing
v JAMES Project (WS 97-98): if seat data is required to be read,
but the seat is not yet implemented, not yet known or only
available by a simulation, provide a bridge:

Seat imp
(in Vehicle Subsystem) SeatImplementation
VIP
GetPosition()
SetPosition()

Stub Code AIMSeat SARTSeat

Bernd Bruegge Component Based Software Engineering 33


JAMES Bridge Example
public interface SeatImplementation {
public int GetPosition();
public void SetPosition(int newPosition);
}
public class AimSeat implements SeatImplementation {
public int GetPosition() {
// actual call to the AIM simulation system
}
….
}
public class SARTSeat implements SeatImplementation {
public int GetPosition() {
// actual call to the SART seat simulator
}
...
}
Bernd Bruegge Component Based Software Engineering 34
Bridge Pattern(151)

Client
imp
Abstraction Implementor
Operation() OperationImpl()

Imp->OperationImp();

Refined Abstraction 1 Refined Abstraction 2 Concrete Implementor A Concrete Implementor B

Operation() Operation() OperationImpl() OperationImpl()

Bernd Bruegge Component Based Software Engineering 35


Adapter vs Bridge

v Similarities:
w Both used to hide the details of the underlying
implementation.
v Difference:
w The adapter pattern is geared towards making unrelated
components work together
u Applied to systems after they’re designed (reengineering,
interface engineering).
w A bridge, on the other hand, is used up-front in a design
to let abstractions and implementations vary
independently.
u Green field engineering of an “extensible system”
u New “beasts” can be added to the “object zoo”, even if these are
not known at analysis or system design time.
Bernd Bruegge Component Based Software Engineering 36
Example for Combination of Adapters and Bridges in
JAMES
Seat Seat Preferences

SetSeatPos() GetSeatPos()

Seat Impl Existing SmartCard


Adapter
Library from
Schlumberger SLBRDR32
Bridge
SLBAPISendIsoOutT0

Seats for the Car

AIMSeat SARTSeat ActualSeat PreferencesCardlet

Bernd Bruegge Component Based Software Engineering 37


Design Patterns encourage good Design Practice

v A facade pattern should be used by all subsystems in a


software system. The façade defines all the services of the
subsystem.
w The facade will delegate requests to the appropriate components
within the subsystem.
v Adapters should be used to interface to any existing
proprietary components.
w For example, a smart card software system should provide an adapter
for a particular smart card reader and other hardware that it controls
and queries.
v Bridges should be used to interface to a set of objects where
the full set is not completely known at analysis or design time.
w Bridges should be used when the subsystem must be extended later
(extensibility).

Bernd Bruegge Component Based Software Engineering 38


Other Design Heuristics

v Never use implementation inheritance, always use interface


inheritance
v A subclass should never hide operations implemented in a
superclass
v If you are tempted to use implementation inheritance, use
delegation instead

Bernd Bruegge Component Based Software Engineering 39


Summary

v Composite Pattern:
w Models trees with dynamic width and dynamic depth
v Facade Pattern:
w Interface to a Subsystem
w Closed vs Open Architecture
v Adapter Pattern:
w Interface to Reality
v Bridge Pattern:
w Interface Reality and Future
v Read and Reread Design Patterns Book
w Learn how to use it as a reference book

Bernd Bruegge Component Based Software Engineering 40


Patterns covered in next Class

v Creational Patterns
w Abstract Factory Pattern (“Device Independence”)
v Structural Patterns
w Proxy (“Location Transparency”)
v Behavioral Patterns
w Command (“Request Encapsulation”, “unlimited undos”)
w Observer (“Publish and Subscribe”)
w Strategy (“Policy vs Mechanism”, “Encapsulate family of
algorithms”)

Bernd Bruegge Component Based Software Engineering 41

You might also like