0% found this document useful (0 votes)
137 views

SA&DP Notes

This document contains lecture notes on software architecture and design patterns. It discusses the following key points: - The introduction defines software architecture as the description of system components, interactions between components, patterns that guide composition, and constraints on those patterns. Architectural descriptions represent systems as boxes and lines. - Unit I covers what software architecture is, architectural styles like pipes and filters, layered systems, and shared information systems. - Subsequent units discuss design patterns including creational, structural, and behavioral patterns. - A case study on designing a document editor is presented to demonstrate applying patterns to solve design problems.

Uploaded by

Nagarjuna Nag
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)
137 views

SA&DP Notes

This document contains lecture notes on software architecture and design patterns. It discusses the following key points: - The introduction defines software architecture as the description of system components, interactions between components, patterns that guide composition, and constraints on those patterns. Architectural descriptions represent systems as boxes and lines. - Unit I covers what software architecture is, architectural styles like pipes and filters, layered systems, and shared information systems. - Subsequent units discuss design patterns including creational, structural, and behavioral patterns. - A case study on designing a document editor is presented to demonstrate applying patterns to solve design problems.

Uploaded by

Nagarjuna Nag
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
You are on page 1/ 112

LECTURE NOTES

ON

SOFTWARE ARCHITECTURE & DESIGN PATTERNS

B.TECH CSE IV YEAR I SEMESTER


(JNTUA-R13)

Mr. P. SURESH
ASST.PROFESSOR

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


CHADALAWADA RAMANAMMA ENGINEERING COLLEGE
CHADALAWADA NAGAR, RENIGUNTA ROAD, TIRUPATI (A.P) - 517506

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 1


JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY ANANTAPUR
B.Tech. IV - I sem
T Tu C
3 1 3

(13A05701) SOFTWARE ARCHITECTURE & DESIGN PATTERNS

UNIT I
Introduction: What is Software Architecture? An Engineering Discipline for Software, The
Status of Software Architecture.
Architectural Styles: Architectural Styles, Pipes and Filters, Data Abstraction and Object-
Oriented Organization, Event-Based, Implicit Invocation, Layered Systems, Repositories,
Interpreters, Process Control, Other Familiar Architectures, Heterogeneous Architectures.
Shared Information Systems: Shared Information Systems, Database Integration, Integration in
Software Development Environments, Architectural Structures for Shared Information Systems.

UNIT II
Introduction: What Is a Design Pattern? Design Patterns in Smalltalk MVC, Describing Design
Patterns, The Catalog of Design Patterns, Organizing the Catalog, How Design Patterns Solve
Design Problems, How to Select a Design Pattern, How to Use a Design Pattern.
Creational Patterns: Abstract Factory, Builder, Factory Method, Prototype, Singleton,
Discussion of Creational Patterns.

UNIT III
Structural Pattern Part-I: Adapter, Bridge, Composite.
Structural Pattern Part-II: Decorator, Facade, Flyweight, Proxy.

UNIT IV
Behavioral Patterns Part-I: Chain of Responsibility, Command, Interpreter, Iterator, Mediator,
Memento, Observer.

UNIT V
Behavioral Patterns Part-II: State, Strategy, Template Method, Visitor, Discussion of
Behavioral Patterns. A Case Study (Designing a Document Editor): Design Problems,
Document Structure, Formatting, Embellishing the User Interface, Supporting Multiple Look-

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 2


and-Feel Standards, Supporting Multiple Window Systems, User Operations, Spelling Checking
and Hyphenation.

Text Books:
1. Design Patterns By Erich Gamma, Pearson Education
2. Software Architecture: Perspective on an Emerging Discipline By Mary Shaw, David
Garlan, PHI.
Reference Books:
1. Software Architecture in Practice by Len Bass, Paul Clements, Rick Kazman, Third
Edition, Pearson Education.
2. Head First Design Patterns By Eric Freeman-Oreilly-spd.
3. Design Patterns Explained By Alan Shalloway, Pearson Education.
4. Pattern Oriented Software Architecture, F.Buschmann & others, John Wiley & Sons
5. Patterns in JAVA Vol-I By Mark Grand, Wiley DreamTech.
6. Patterns in JAVA Vol-II By Mark Grand, Wiley DreamTech.
7. JAVA Enterprise Design Patterns Vol-III By Mark Grand, Wiley DreamTech

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 3


UNIT -I

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 4


UNIT-I
Introduction to Software Architecture

1.1 What is Software Architecture?


As the size and complexity of software systems increase, the design and specification of
overall system structure become more significant issues than the choice of algorithms and
data structures of computation.
Software architecture involves the description of elements from which systems are built,
interactions among these elements, patterns that guide their composition, and constraints on
these patterns.
A particular system is defined as a collection of components and interactions among
those components. Such a system may be used as a (composite) element in a larger system.
Architectures are represented abstractly as box-and-line diagrams.
Architectural descriptions serve as a skeleton around which system properties can be
fleshed out. So they play a vital role in exposing the ability of a system to meet its major
system requirements.
The architecture of a software system defines that system in terms of computational
components and interactions among those components.
Components: clients & servers, databases, filters, and layers in a hierarchical system.
Interactions at this level of design can be simple and familiar. Ex: procedure calls, shared
variable access.
But they can also be complex and semantically rich. Ex: client-server protocols, database
accessing protocols, synchronous event multicast, and piped streams.
In addition to structure and topology the architecture shows the correspondence between
the system requirements and elements of the constructed system.
1.1.1 Software Design Levels:
System design takes place at many levels. At each level we find
-components, both primitive and composite;
-rules of composition that allow the construction of non-primitive components or
systems;
-rules of behavior that provide semantics for the system.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 5


There may be different notations, design problems, analysis techniques at each level.
Software, too, has its design levels.
1. Architecture:
 The design issues involve overall association of system capability with
components.
 Components are modules, and inter connections among modules are handled in a
variety of ways.
 Operators guide the composition of systems from subsystems.
2. Code:
 The design issues involve algorithms and data structures.
 The components are programming language primitives such as numbers,
characters, pointers, and threads of control.
 Primitive operators are the arithmetic and data manipulation primitives of the
language.
 Composition mechanisms include records, arrays, and procedures.
3. Executable:
 The design issues involve memory maps, data layouts, call stacks, and register
allocations.
 The components are bit patterns supported by hardware.
 The operations and compositions are described in machine code.
Our concern here is to improve understanding and precision at the software architecture
level. At this level the components are programs, modules. or systems; a rich collection
of interchange representations and protocols connects the components; and system
patterns often guide the compositions.
1.2 An Engineering Discipline for Software:
1.2.1 What is Engineering?
Software engineering is a label applied to a set of current practices for software
development. The more common usage refers to the disciplined application of scientific
knowledge to resolve conflicting constraints and requirements for problems of immediate,
practical significance.
Definitions of engineering share some common clauses:

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 6


Creating cost-effective solutions…..
.... to practical problems
…. by applying scientific knowledge...
…. building things...
…. in the service of mankind
Routine and Innovative Design
Engineering design tasks are of several kinds; one of the most significant distinctions
among them separates routine from innovative design.
Routine Design: involves solving familiar problems, reusing large portions of prior
solutions.
Innovative Design: It involves finding novel solutions to unfamiliar problems.
 One path to increased productivity is identifying applications that could be routine and
developing appropriate support.
A Model for the Evolution of Engineering Discipline
Engineering has emerged from ad hoc practice in two stages.
1. Management and production techniques enable routine production.
2. The problems of routine production stimulate the development of a supporting science; the
mature science eventually merges with established practice to yield professional engineering
practice.

Fig: Evolution of an Engineering Discipline


The lower lines track the technology, and the upper lines show how the entry of production
skills and scientific knowledge contribute new capability to the engineering practice.
1.2.2 The Current State of Software Technology
The engineering problem is creating cost-effective solutions to practical problems... building
things in the service of mankind.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 7


Scientific basis for Engineering practice
Engineering practice emerges from commercial practice by exploiting the results of a
companion science.
Maturity of supporting science:
 Each program contains algorithms and data structures.
 Algorithms and data structures began to be abstracted from individual programs.
Research on abstract data types dealt with such issues as the following:
- Specifications {abstract models, algebraic axioms)
- Software structure (bundling representation with algorithms)
- Language issues (modules, scope, user-defined types)
- Information hiding (protecting integrity of information not in specification]
- Integrity constraints (invariants of data structures)
- Rules for composition (declarations)
Interaction between Science and Engineering:
The development of good models within the software domain follows the pattern of
following figure.

Fig: Codification Cycle for Science and Engineering

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 8


Fig: Evolution of Software Engineering

Codification through Abstraction Mechanisms:


One characteristic of progress in programming languages and tools has been regular increases
in abstraction level—or the conceptual size of the building blocks used by software designers.
The conversion from an intuition to a theory involved understanding the following:
The software structure, Specifications, Language issues, Integrity of the result, Rules for
combining types, Information hiding.

1.3 The Status of Software Architecture:


Good architectural design has always been a major factor in determining the success of a
software system. Recently, software architecture has begun to emerge as an important field of
study for software engineering practitioners and researchers.
Architectural issues are being addressed by work in areas such as module interface
languages, domain-specific architectures, software reuse, codification of organizational
patterns for software, architectural description languages and architectural design
environments.
Two recent workshops brought together researchers and practitioners interested in
software architecture to discuss the current state of the practice and art.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 9


These workshops served to establish a common understanding of the state of the practice,
the kinds of research and development efforts that are in progress, and the important
challenges for this emerging field. Widespread interest in these workshops demonstrates the
extent of these activities, which can be roughly placed into four categories.
 Addressing the problem of architectural characterization by providing new
architectural description languages.
 Addressing the codification of the architectural expertise.
 Addressing frameworks for specific domains.
 Addressing formal underpinnings for architecture.
Software architecture provides benefits for both development and maintenance. For
development, effective software engineers require facility in architectural software design.
 Able to recognize common paradigms
 Getting the right architecture
 Detailed understanding of software architecture
 Architectural system representation
 Fluency in the use of notations
Beyond the development stage, documenting a system‟s structure and properties has
various advantages for maintenance. Much of the time spent on maintenance goes to
understanding the existing code. Retaining the designers intentions about system organization
should help maintainers preserve the system„s design integrity.

1.4 Architectural Styles:


An architectural pattern is a general, reusable solution to a commonly occurring
problem in software architecture within a given context. The architectural patterns address
various issues in software engineering, such as computer hardware performance limitations,
high availability and minimization of a business risk. Some architectural patterns have been
implemented within software frameworks.
An architectural style defines: a family of systems in terms of a pattern of structural
organization; a vocabulary of components and connectors, with constraints on how they can
be combined.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 10


Some treat architectural patterns and architectural styles as the same, some treat styles as
specializations of patterns.
The main difference is that a pattern can be seen as a solution to a problem, while a style
is more general and does not require a problem to solve for its appearance.
List of common architectural styles:
Dataflow systems: Virtual machines:
Batch sequential Interpreters
Pipes and filters Rule-based systems
Call-and-return systems: Data-centered systems:
Main program and subroutine Databases
OO systems Hypertext systems
Hierarchical layers Blackboards
Independent components:
Communicating processes
Event systems

1.5 Pipes and Filters:


 Each components has set of inputs and set of outputs
 A component reads streams of data on its input and produces streams of data on its
output.
 By applying local transformation to the input streams and computing incrementally, so
that output begins before input is consumed. Hence, components are termed as filters.
 Connectors of this style serve as conducts for the streams transmitting outputs of one
filter to inputs of another. Hence, connectors are termed pipes.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 11


Conditions (invariants) of this style are:
 Filters must be independent entities.
 They should not share state with other filter
 Filters do not know the identity of their upstream and downstream filters.
 Specification might restrict what appears on input pipes and the result that appears on the
output pipes.
 Correctness of the output of a pipe-and-filter network should not depend on the order in
which filter perform their processing.
Common specialization of this style includes:
 Pipelines: Restrict the topologies to linear sequences of filters.
 Bounded pipes: Restrict the amount of data that can reside on pipe.
 Typed pipes: Requires that the data passed between two filters have a well-defined type.
Batch sequential system:
A degenerate case of pipeline architecture occurs when each filter processes all of its
input data as a single entity. In these systems pipes no longer serve the function of providing a
stream of data and are largely vestigial.

Example 1: Best known examples of pipe-and-filter architecture are programs written in UNIX-
SHELL. Unix supports this style by providing a notation for connecting components [Unix
process] and by providing run-time mechanisms for implementing pipes.

Example 2: Traditionally compilers have been viewed as pipeline systems. Stages in the pipeline
include lexical analysis parsing, semantic analysis and code generation other examples of this
type are.
 Signal processing domains
 Parallel processing
 Functional processing
 Distributed systems.
Advantages:
 They allow the designer to understand the overall input/output behavior of a system as a
simple composition of the behavior of the individual filters.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 12


 They support reuse: Any two filters can be hooked together if they agree on data.
 Systems are easy to maintain and enhance: New filters can be added to exciting systems.
 They permit certain kinds of specialized analysis eg: deadlock, throughput
 They support concurrent execution.
Disadvantages:
 They lead to a batch organization of processing.
 Filters are independent even though they process data incrementally.
 Not good at handling interactive applications
o When incremental display updates are required.
o They may be hampered by having to maintain correspondences between two
separate but related streams.
o Lowest common denominator on data transmission.
 This can lead to both loss of performance and to increased complexity in writing the
filters.
1.6 Data Abstraction and Obiect-Oriented Organization:
In this approach, data representation and their associated primitive operations are
encapsulated in the abstract data type (ADT) or object. The components of this style are-
objects/ADT‟s objects interact through function and procedure invocations. Objects are
examples of a type of component we call a manager because it is responsible for preserving the
integrity of a resource.
Two important aspects of this style are:
 Object is responsible for preserving the integrity of its representation.
 Representation is hidden from other objects.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 13


Fig: Abstract Data Types and Objects
Advantages:
 It is possible to change the implementation without affecting the clients because an object
hides its representation from clients.
 The bundling of a set of accessing routines with the data they manipulate allows
designers to decompose problems into collections of interacting agents.
Disadvantages:
 To call a procedure, it must know the identity of the other object.
 Whenever the identity of object changes it is necessary to modify all other objects that
explicitly invoke it.
1.7 Event-Based, Implicit Invocation:
 Instead of invoking the procedure directly a component can announce one or more
events.
 Other components in the system can register an interest in an event by associating a
procedure to it.
 When the event is announced, the system itself invokes all of the procedure that have
been registered for the event. Thus an event announcement “implicitly” causes the
invocation of procedures in other modules.
 Architecturally speaking, the components in an implicit invocation style are modules
whose interface provides both a collection of procedures and a set of events.
Advantages:
 It provides strong support for reuse

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 14


 Any component can be introduced into the system simply by registering it for the events
of that system.
 Implicit invocation eases system evolution.
 Components may be replaced by other components without affecting the interfaces of
other components.
Disadvantages:
 Components relinquish control over the computation performed by the system.
 Concerns change of data
 Global performance and resource management can become artificial issues.

1.8 Layered Systems:


 A layered system is organized hierarchically, each layer provides service to the layer
above it and serving as a client to the layer below.
 Inner layers are hidden from all except the adjacent layers.
 Connectors are defined by the protocols that determine how layers interact with each
other.
 Goal is to achieve qualities of modifiability portability.

Fig: Layered Systems

Examples:
 Layered communication protocol
 Operating systems

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 15


 Database systems
Advantages:
 They support designs based on increasing levels abstraction.
 Allows implementers to partition a complex problem into a sequence of incremental
steps.
 They support enhancement
 They support reuse.
Disadvantages:
 Not easily all systems can be structures in a layered fashion.
 Performance may require closer coupling between logically high-level functions and their
lower-level implementations.
 Difficulty to mapping existing protocols into the ISO framework as many of those
protocols bridge several layers.
Layer bridging: functions in one layer may talk to other than its immediate neighbor.

1.9 Repositories: [data cantered architecture]


 Goal of achieving the quality of integrability of data.
 In this style, there are two kinds of components.
i. Central data structure- represents current state.
ii. Collection of independent components which operate on central data store.
The choice of a control discipline leads to two major sub categories.
 Type of transactions is an input stream trigger selection of process to execute
 Current state of the central data structure is the main trigger for selecting processes to
execute. The Active repository can be a blackboard.
Blackboard:
Three major parts:
 Knowledge sources: Separate, independent parcels of application dependents
knowledge.
 Blackboard data structure: Problem solving state data, organized into an application-
dependent hierarchy
 Control: Driven entirely by the state of blackboard
Invocation of a knowledge source (ks) is triggered by the state of blackboard.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 16


Fig: The Blackboard
The actual focus of control can be in
- Knowledge source
- Blackboard
- Separate module or
- Combination of these
Blackboard systems have traditionally been used for application requiring complex interpretation
of signal processing like speech recognition, pattern recognition.
1.10 Interpreters:
 An interpreter includes pseudo program being interpreted and interpretation engine.
 Pseudo program includes the program and activation record.
 Interpretation engine includes both definition of interpreter and current state of its
execution.
Interpreter includes 4 components:
1. Interpretation engine: to do the work
2. Memory: that contains pseudo code to be interpreted.
3. Representation of control state of interpretation engine
4. Representation of control state of the program being simulated.
Ex: JVM or “virtual Pascal machine”
Advantages:
Executing program via interpreters adds flexibility through the ability to interrupt and
query the program

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 17


Disadvantages:
Performance cost because of additional computational involved

Fig: Interpreter

1.11 Process Control:


This architectural style is based on control loops.
 Object-oriented and functional designs are characterized by the kinds of components that
appear.
 Control loop designs are characterized by both the kinds of components involved and the
special relations that must hold among them.
Process Control Paradigms:
Continuous processes of many kinds convert input materials to products with specific
properties by performing operations on the inputs and on intermediate products.
Process Control Definitions:
Process variables: properties of the process that can be measured
Controlled variable: process variable whose value of the system is intended to control
Input variable: process variable that measures an input to the process
Manipulated variable: process variable whose value can be changed by the controller

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 18


Set point: the desired value for a controlled variable
Open-loop system: system in which information about process variables is not used to adjust the
system
Closed-loop system: system in which information about process variables is used to manipulate a
process variable to compensate for variations in process variables and operating conditions
Feedback control system: the controlled variable is measured and the result is used to manipulate
one or more of the process variables
Feed forward control system: some of the process variables are measured, and anticipated
disturbances are compensated without waiting for changes in the controlled variable to be
visible.
The open-loop assumptions are rarely valid for physical processes in the real world. More
often, properties such as temperature, pressure and flow rates are monitored, and their values are
used to control the process by changing the settings of apparatus such as valve, heaters and
chillers. Such systems are called closed loop systems.

Fig: open-loop temperature control


A home thermostat is a common example; the air temperature at the thermostat is
measured, and the furnace is turned on and off as necessary to maintain the desired temperature.
Below figure shows the addition of a thermostat to convert above figure to a closed loop system.

Fig: closed-loop temperature control

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 19


Feedback control:
Above figure corresponds to below figure as follows:
 The furnace with burner is the process
 The thermostat is the controller
 The return air temperature is the input variable
 The hot air temperature is the controlled variable
 The thermostat setting is the set point
 Temperature sensor is the sensor

Fig: feedback control

Feedforward control:
It anticipates future effects on the controlled variable by measuring other process
variables and adjusts the process based on these variables. The important components of a feed
forward controller are essentially the same as for a feedback controller except that the sensor(s)
obtain values of input or intermediate variables.

Fig: feed forward control

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 20


 These are simplified models
 They do not deal with complexities - properties of sensors, transmission delays &
calibration issues
 They ignore the response characteristics of the system, such as gain, lag and hysteresis.
 They don‟t show how combined feed forward and feedback
 They don‟t show how to manipulate process variables.
A Software Paradigm for Process Control:
An architectural style for software that controls continuous processes can be based on the
process-control model, incorporating the essential parts of a process-control loop:
Computational elements: separate the process of interest from the controlled policy
 Process definition, including mechanisms for manipulating some process variables
 Control algorithm, for deciding how to manipulate variables
Data element: continuously updated process variables and sensors that collect them
 Process variables, including designed input, controlled and manipulated variables and
knowledge of which can be sensed
 Set point, or reference value for controlled variable
 Sensors to obtain values of process variables pertinent to control
The control loop paradigm: establishes the relation that the control algorithm exercises.

1.12 Other Familiar Architectures:


 Distributed processes: Distributed systems have developed a number of common
organizations for multi-process systems. Some can be characterized primarily by their
topological features, such as ring and star organizations. Others are better characterized in
terms of the kinds of inter-process protocols that are used for communication (e.g.,
heartbeat algorithms).
 Main program/subroutine organizations: The primary organization of many systems
mirrors the programming language in which the system is written. For languages without
support for modularization this often results in a system organized around a main
program and a set of subroutines.
 Domain-specific software architectures: These architectures provide an organizational
structure tailored to a family of applications, such as avionics, command and control, or

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 21


vehicle management systems. By specializing the architecture to the domain, it is
possible to increase the descriptive power of structures.
 State transition systems: These systems are defined in terms a set of states and a set of
named transitions that move a system from one state to another.

1.13 Heterogeneous Architectures:


Architectural styles can be combined in several ways:
 One way is through hierarchy. Example: UNIX pipeline
 Second way is to combine styles is to permit a single component to use a mixture of
architectural connectors. Example: “active database”
 Third way is to combine styles is to completely elaborate one level of architectural
description in a completely different architectural style. Example: case studies
1.14 Shared Information Systems:
One particularly significant class of large systems is responsible for collecting,
manipulating, and preserving large bodies of complex information. These are shared information
systems.
Systems of this kind appear in many different domains, mainly
 Data Processing: Driven primarily by the need to build business decision systems
from conventional databases.
 Software Development Environment: Driven primarily by the need to represent and
manipulate programs and their designs.
 Building Design: Driven primarily by the need to couple independent design tools to
allow for the interactions of their results in structural design.
The earliest shared information systems consisted of separate programs for separate
subtasks. Later, multiple independent processing steps were composed into larger tasks by
passing data in a known, fixed format from one step to another.
This organization is
 not flexible
 not tolerant for structural modification
 not responsive to the needs of interactive processing

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 22


New organizations allowed independent processing subsystems to interact through a shared
data store. While this organization is an improvement, it still encounters integration problems-
especially when multiple data stores with different representations must be shared, when the
system is distributed, when many user tasks must be served, and when the suite of processing
and data subsystems changes regularly.

1.15 Database Integration:


Business data processing has traditionally been dominated by database management, in
particular by database updates. Originally, separate databases served separate purposes, and
implementation issues revolved around efficient ways to do massive coordinated periodic
updates. Interactive demands required individual transactions to complete in real time.
Information began to appear redundantly in multiple databases, and geographic distribution
added communication complexity.
Individual database systems must support transactions of predetermined types and periodic
summary reports. Bad requests require a great deal of special handling. Originally the updates
and summary reports were collected into batches, with database updates and reports produced
during periodic batch runs.
As databases became more common, information about a business became distributed
among multiple databases. Hence data become inconsistent and incomplete. The representations,
or schemas, for different databases were usually different; even the portion of the data shared by
two databases is likely to have representations in each database. The total volume of data to
handle is correspondingly larger, and it is often distributed across multiple machines. Two
general strategies emerged for dealing with data diversity:
 unified schemas
 multi-databases.

1.15.1 Batch Sequential:


Some of the earliest large computer applications were databases. In these applications
individual database operations-transactions-were collected into large batches. The application
consisted of a small number of large standalone programs that performed sequential updates on
flat (unstructured) files. Atypical organization included:

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 23


 a massive edit program: accepts transaction inputs and perform validation without
accessing the database.
 a massive transaction sort: get transactions into the same order as the records on the
sequential master file
 a sequence of update programs: one for each master file; these huge programs actually
executed the transactions by moving sequentially through the master file, matching each
type of transaction to its corresponding account and updating the account records.
 a print program: produce periodic reports
Batch sequential architecture:
The steps were independent of each other; they had to run in a fixed sequence; each ran to
completion, producing an output file in a new format, before the next step began.

Fig: Data flow diagram for batch databases

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 24


The above figure shows the possibility of on-line queries (but not modifications).In this structure
the files to support the queries are reloaded periodically, so recent transactions (e.g., within the
past few days) are not reflected in the query responses.
Above figure is a Yourdon data flow diagram. Processes are depicted as circles, or
"bubbles"; data flow (here, large files) is depicted with arrows, and data stores such as computer
files are depicted with parallel lines.

Fig: Internal structure of batch update process


Above figure shows the internal structure of an update process. There is one of these for
each of the master data files, and each is responsible for handling all possible updates to that data
file. Here, the boxes represent subprograms and the lines represent procedure calls. A single
driver program processes all batch transactions. Each transaction has a standard set of
subprograms that check the transaction request, access the required data, validate the transaction,
and post the result. Thus all the program logic for each transaction is localized in a single set of
subprograms.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 25


The redrawn figure emphasizes the sequence of operations to be performed and the
completion of each step before the start of its successor. It suppresses the on-line query support
and updates to multiple master files, or databases.

Fig: Batch sequential database architecture


1.15.2 Simple Repository:
Two trends forced a change away from batch sequential processing.
 First, interactive technology provided the opportunity and demand for continuous
processing of on-line updates as well as on-line queries.
 Second, as organizations grew, the set of transactions and queries grew.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 26


 Here, the transaction database and extract database are transient buffers; the
account/item database is the central permanent store.
 The transaction database serves to synchronize multiple updates.
 The extract database solves a problem created by the addition of interactive processing
namely the loss of synchronization between the updating and reporting cycles.
 It is useful to separate the general overhead operations from the transaction-specific
operations.
 It may also be useful to perform multiple operations on a single account all at once.

The system structure is easier to understand if we first isolate the database updates. Figure 7
focuses narrowly on the database and its transactions. This is an instance of a fairly common
architecture, a repository, in which shared persistent data is manipulated by independent
functions each of which has essentially no permanent state. It is the core of a database system.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 27


Figure 8 adds two additional structures. The first is a control element that accepts the batch
or interactive stream of transactions, synchronizes them, and selects which update or query
operations to invoke, and in which order. This subsumes the transaction database of Figure 5.
The second is a buffer that serves the periodic reporting function. This subsumes the extract
database of Figure 5.

1.15.3 Virtual Repository:


 As organizations grew, databases came to serve multiple functions.
 Corporate reorganizations, mergers, and other consolidations of data forced the joint use
of multiple databases.
 As a result, information could no longer be localized in a single database.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 28


 Developing applications that rely on multiple diverse databases requires solution of two
problems.
 First, the system must reconcile representation differences.
 Second, it must communicate results across distributed systems that may have not only
different data representations but also different database schema representations.
 One approach to the unification of multiple schemas is called the federated approach.
 The top of this figure shows how the usual database mechanisms integrate multiple
schemas into a single schema.
 The bottom of the figure suggests an approach to importing data from autonomous
external databases:
 For each database, devise a schema in its native schema language that exports the desired
data and a matching schema in the schema language of the importer.
 This separates the solutions to the two essential problems and restricts the distributed
system problem to communication between matching schemas.

Fig: Combining multiple distributed schemas


P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 29
 Figure 11 shows the integration of multiple databases by unified schemas.
 It shows a simple composition of projections.
 The details about whether the data paths are local or distributed and whether the local
schema and import schema are distinct are suppressed at this level of abstraction;

1.15.4 Hierarchical Layers:


 Unified schemas allow for merger of information, but their mappings are fixed, passive,
and static.
 The mappings simply transform the underlying data; and there are essentially no
provisions for recognizing and adapting to changes in the set of available databases.
 The details about whether the data paths are local or distributed and whether the local
schema and import schema are distinct are suppressed at this level of abstraction;
 In the real world, each database serves multiple users, and indeed the set of users changes
regularly.
 The set of available databases also changes, both because the population of databases
itself changes and because network connectivity changes the set that is accessible.
 Problems: inconsistency across a set of databases, dynamic reconfiguration.
Below fig. depicts one research scenario for active mediation between a constantly-changing set
of users and a constantly changing set of databases.
 Wiederhold proposes introducing active programs, called experts, to accept queries from
users, recast them as queries to the available databases, and deliver appropriate responses
to the users.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 30


 These experts, or active mediators, localize knowledge about how to discover what
databases are available and interact with them, about how to recast user‟s queries in
useful forms, and about how to reconcile, integrate, and interpret information from
multiple diverse databases.

Fig: Multi-database with mediator


 In effect, Wiederhold's architecture uses hierarchical layers to separate the business of the
users, the databases, and the mediators.
 The interaction between layers of the hierarchy will most likely be a client-server
relation.
 This is not a repository because there is no enforced coherence of central shared data; it is
not a batch sequential system (or any other form of pipeline) because the interaction with
the data is incremental.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 31


1.15.5 Evolution of Shared Information Systems in Business Data Processing:
 These business data processing applications exhibit a pattern of development driven by
changing technology and changing needs. The pattern was:
 Batch processing: Standalone programs; results are passed from one to another on
magtape. Batch sequential model.
 Interactive processing: Concurrent operation and faster updates preclude batching, so
updates are out of synchronization with reports. Repository model with external control.
 Unified schemas: Information becomes distributed among many different databases.
One virtual repository defines (passive) consistent conversion mappings to multiple
databases.
 Multi-database: Databases have many users; passive mappings don't suffice; active
agents mediate interactions. Layered hierarchy with client-server interaction.
 In this evolution, technological progress and expanding demand drive progress.
 Larger memories and faster processing enable access to an ever-wider assortment of data
resources in a heterogeneous, distributed world.
 Our ability to exploit this remains limited by volume, complexity of mappings, the need
to handle data discrepancies, and the need for sophisticated interpretation of requests for
services and of available data.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 32


1.16 Integration in Software Development Environments:
 Software development has relied on software tools whereas data processing has relied on
on-line databases.
 Initially these tools only supported the translation from source code to object code; they
included compilers, linkers, and libraries.
 Tools now support analysis, configuration control, debugging, testing, and documentation
as well.
Batch Sequential:
 The earliest software development tools were standalone programs.
 Often their output appeared only on paper and maybe in the form of object code on cards
or paper tape.
 The output of each tool was most likely in the wrong format, the wrong units, or the
wrong conceptual model for other tools to use.
 Effective sharing of information was thus limited by lack of knowledge about how
information was encoded in representations.
 As a result, manual translation of one tool's output to another tool's input format was
common.
 Later, new tools incorporated prior knowledge of related tools, and the usefulness of
shared information became more evident.
 Scripts grew up to invoke tools in fixed orders. These scripts essentially defined batch
sequential architectures.
 This remains the most common style of integration for most environments.
Transition from Batch Sequential to Repository:
 Our view of the architecture of a system can change in response to improvements in
technology.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 33


 We often refer to this compilation model as a pipeline, even though it was closer to a
batch sequential architecture in which each transformation (“pass”) ran to completion
before the next one started.
 Symbol Table was not part of the data that flowed from one pass to another but rather
existed outside all the passes.
 The algorithms and representations of compilation grew more complex, and increasing
attention turned to the intermediate representation of the program during compilation.

 A more appropriate view of this structure would re-direct attention from the sequence of
passes to the central shared representation.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 34


 When you declare that the tree is the locus of compilation information and the passes
define operations on the tree.
 This new view also accommodates various tools that operate on the internal
representation rather than the textual form of a program; these include syntax-directed
editors and various analysis tools.
 The execution order of the operations in the database was determined by the types of the
incoming transactions, the execution order of the compiler is predetermined, except
possibly for opportunistic optimization.

Repository:
 Batch sequential tools and compilers--even when organized as repositories do not retain
information from one use to another. As a result, a body of knowledge about the program
is not accumulated.
 The repository of the compiler provided a focus for this data collection.
 Some of the ways that tools could interact with a shared repository.
 Tight coupling: Share detailed knowledge of the common, but proprietary,
representation among the tools of a single vendor
 Open representation: Publish the representation so that tools can be developed by many
sources. Often these tools can manipulate the data, but they are in a poor position to
change the representation for their own needs.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 35


 Conversion boxes: Provide filters that import or export the data in foreign
representations. The tools usually lose the benefits of incremental use of the repository.
 No contact: Prevent a tool from using the repository, either explicitly, through excess
complexity, or through frequent changes.

Hierarchical Layers:
 Current work on integration emphasizes interoperability of tools, especially in distributed
systems.
 It resembles in some ways the layered architecture with mediators for databases, but it is
more elaborate because it attempts to integrate communications and user interfaces as
well as representation.
 It also embeds knowledge of software development processes, such as the order in which
tools must be used and what situations call for certain responses.
 This model provides for integration of data, it provides communication and user interface
services directly.
 The integration system defined a set of "events" (e.g., "module foo.c recompiled") and
provides support for tools to announce or to receive notice of the occurrence of events.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 36


1.17 Evolution of Shared Information Systems in Software Development
Environments:
 Software development has different requirements from database processing.
 As compared to databases, software development involves more different types of data,
fewer instances of each distinct type, and slower query rates.
 The units of information are larger, more complex, and less discrete than in traditional
databases.
 Here the forces for evolution were:
 the advent of on-line computing, which drove the shift from batch to interactive
processing for many functions

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 37


 the concern for efficiency, which is driving a reduction in the granularity of
operations, shifting from complete processing of systems to processing of
modules to incremental development
 the need for management control over the entire software development process,
which is driving coverage to increase from compilation to the full life cycle.
 Integration in this area is still incomplete.
 Data conversions are passive, and the ordering of operations remains relatively inflexible.
 Software development environments are under pressure to add capabilities for handling
complex dependencies and selecting which tools to use.
 Current software tools do not distinguish among different kinds of components at this
level.
 These tools treat all modules equally, and they mostly assume that modules interact only
via procedure calls and perhaps shared variables.
 The use of well-known patterns leads to a kind of reuse of design templates.

Variants on Data Flow Systems:


 The data flow architecture that repeatedly occurs in the evolution of shared information
systems is the batch sequential pattern.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 38


UNIT -II

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 39


UNIT-II
Introduction to Design Patterns

2.1 What Is a Design Pattern?


Christopher Alexander says, "Each 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 this solution a million times over, without ever doing it the same
way twice".
In general, a pattern has four essential elements:
1. Pattern Name:
 It is a handle we can use to illustrate a design problem, its solutions, and
consequences in a word or two.
 Naming a pattern instantly increases our design vocabulary. It lets us design at a
higher level of abstraction.
 It makes it easier to think about designs and to communicate them and their trade-
offs to others.
 Finding good names has been one of the hardest parts of developing our catalog.
2. Problem:
 It describes when to apply the pattern.
 It explains the problem and its context.
 It might describe specific design problems such as how to represent algorithms as
objects.
 It might describe class or object structures that are indicative of an inflexible
design.
 Sometimes the problem will include a list of conditions that must be met before it
makes sense to apply the pattern.
3. Solution:
 It describes the elements that make up the design, their relationships,
responsibilities, and collaborations.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 40


 The solution doesn't describe a particular concrete design or implementation,
because a pattern is like a template that can be applied in many different
situations.
 Instead, the pattern provides an abstract description of a design problem and how
a general arrangement of elements solves it.
4. Consequences:
 They are the results and trade-offs of applying the pattern.
 Though consequences are often understood when we describe design decisions,
they are critical for evaluating design alternatives and for understanding the costs
and benefits of applying the pattern.
 The consequences for software often concern space and time trade-offs.
 They may address language and implementation issues as well.
 Since reuse is often a factor in object-oriented design, the consequences of a
pattern include its impact on a system's flexibility, extensibility, or portability.
 Listing these consequences explicitly helps you understand and evaluate them.
Point of view affects one's interpretation of what is and isn't a pattern. One person's
pattern can be another person's primitive building block.
The design patterns are descriptions of communicating objects and classes that are
customized to solve a general design problem in a particular context.
 A design pattern names, abstracts, and identifies the key aspects of a common design
structure that make it useful for creating a reusable object-oriented design.
 The design pattern identifies the participating classes and instances, their roles and
collaborations, and the distribution of responsibilities.
 Each design pattern focuses on a particular object-oriented design problem or issue.
 It describes when it applies, whether it can be applied in view of other design constraints,
and the consequences and trade-offs of its use.
 Although design patterns describe object-oriented designs, they are based on practical
solutions that have been implemented in mainstream object-oriented programming
languages like Smalltalk and C++ rather than procedural languages(Pascal, C, Ada) or
more dynamic object-oriented languages (CLOS, Dylan, Self).

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 41


 The choice of programming language is important because it influences one's point of
view. Our patterns assume Smalltalk/C++-level language features, and that choice
determines what can and cannot be implemented easily.
 If we assumed procedural languages, we might have included design patterns called
"Inheritance", "Encapsulation," and "Polymorphism."

2.2 Design Patterns in Smalltalk MVC


The Model/View/Controller (MVC) triad of classes is used to build user interfaces in
Smalltalk-80.MVC consists of three kinds of objects. The Model is the application object,
the View is its screen presentation, and the Controller defines the way the user interface
reacts to user input. Before MVC, user interface designs tended to combine these objects
together. MVC decouples them to increase flexibility and reuse.
 MVC decouples views and models by establishing a subscribe/notify protocol
between them.
 A view must ensure that its appearance reflects the state of the model.
 Whenever the model's data changes, the model notifies views that depend on it.
 In response, each view gets an opportunity to update itself.
 This approach lets you attach multiple views to a model to provide different
presentations.
 We can also create new views for a model without rewriting it.
The following diagram shows a model and three views.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 42


 The model contains some data values, and the views defining a spreadsheet,
histogram, and pie chart display these data in various ways.
 The model communicates with its views when its values change, and the views
communicate with the model to access these values.

This example reflects a design that decouples views from models. But the design is
applicable to a more general problem: decoupling objects so that changes to one can affect
any number of others without requiring the changed object to know details of the others. This
more general design is described by the Observer design pattern.

Another feature of MVC is that views can be nested. For example, a control panel of buttons
might be implemented as a complex view containing nested button views. MVC supports
nested views with the CompositeView class, a subclass of View.

But the design is applicable to a more general problem, which occurs whenever we want to
group objects and treat thegroup like an individual object. This more general design is
described by the Composite design pattern.

MVC also lets you change the way a view responds to user input without changing its visual
presentation. You might want to change the way it responds to the keyboard, for example, or
have it use a pop-up menu instead of command keys. MVC encapsulates the response
mechanism in a Controller object.

A view uses an instance of a Controller subclass to implement a particular response strategy;


to implement a different strategy, simply replace the instance with a different kind of
controller.

The View-Controller relationship is an example of the Strategy design pattern. A Strategy is


an object that represents an algorithm.

MVC uses other design patterns, such as Factory Method to specify the default controller
class for a view and Decorator to add scrolling to a view. But the main relationships in MVC
are given by the Observer, Composite, and Strategy design patterns.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 43


2.3 Describing Design Patterns

Describing the design patterns in graphical notations, simply capture the end product of
the design process as relationships between classes and objects.

We describe design patterns using a consistent format. Each pattern is divided into
sections according to the following template. The template lends a uniform structure to the
information, making design patterns easier to learn, compare, and use.
Pattern Name and Classification
The pattern's name conveys the essence of the pattern succinctly. A good name is vital,
because it will become part of your design vocabulary.
Intent
This describes, what does the design pattern do? What is its rationale and intent? What
particular design issue or problem does it address?
Also Known As
Other well-known names for the pattern, if any.
Motivation
A scenario that illustrates a design problem and how the class and object structures in the
pattern solve the problem. The scenario will help you understand the more abstract
description of the pattern that follows.
Applicability
What are the situations in which the design pattern can be applied? What are examples of
poor designs that the pattern can address? How can you recognize these situations?
Structure
A graphical representation of the classes in the pattern using a notation based on the
Object Modeling Technique (OMT). We also use interaction diagrams to illustrate
sequences of requests and collaborations between objects.
Participants
The classes and/or objects participating in the design pattern and their responsibilities.
Collaborations
How the participants collaborate to carry out their responsibilities.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 44


Consequences
How does the pattern support its objectives? What are the trade-offs and results of using
the pattern? What aspect of system structure does it let you vary independently?
Implementation
What pitfalls, hints, or techniques should you be aware of when implementing the
pattern? Are there language-specific issues?
Sample Code
Code fragments that illustrate how you might implement the pattern in C++ or Smalltalk.
Known Uses
Examples of the pattern found in real systems. We include at least two examples from
different domains.
Related Patterns
What design patterns are closely related to this one? What are the important differences?
With which other patterns should this one be used?
2.4 The Catalog of Design Patterns
The catalog contains 23 design patterns. Their names and intents are listed below.
1. Abstract Factory
Provide an interface for creating families of related or dependent objects without
specifying their concrete classes.
2. 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.
3. Bridge
Decouple an abstraction from its implementation so that the two can vary independently.
4. Builder
Separate the construction of a complex object from its representation so that the same
construction process can create different representations.
5. Chain of Responsibility
Avoid coupling the sender of a request to its receiver by giving more than one object a
chance to handle the request. Chain the receiving objects and pass the request along the
chain until an object handles it.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 45


6. Command
Encapsulate a request as an object, thereby letting you parameterize clients with different
requests, queue or log requests, and support undoable operations.
7. Composite
Compose objects into tree structures to represent part-whole hierarchies. Composite lets
clients treat individual objects and compositions of objects uniformly.
8. Decorator
Attach additional responsibilities to an object dynamically. Decorators provide a flexible
alternative to subclassing for extending functionality.
9. 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.
10. Factory Method
Define an interface for creating an object, but let subclasses decide which class to
instantiate. Factory Method lets a class defer instantiation to subclasses.
11. Flyweight
Use sharing to support large numbers of fine-grained objects efficiently.
12. Interpreter
Given a language, define a representation for its grammar along with an interpreter that
uses the representation to interpret sentences in the language.
13. Iterator
Provide a way to access the elements of an aggregate object sequentially without
exposing its underlying representation.
14. Mediator
Define an object that encapsulates how a set of objects interact. Mediator promotes loose
coupling by keeping objects from referring to each other explicitly, and it lets you vary
their interaction independently.
15. Memento
Without violating encapsulation, capture and externalize an object's internal state so that
the object can be restored to this state later.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 46


16. Observer
Define a one-to-many dependency between objects so that when one object changes state,
all its dependents are notified and updated automatically.
17. Prototype
Specify the kinds of objects to create using a prototypical instance, and create new
objects by copying this prototype.
18. Proxy
Provide a surrogate or placeholder for another object to control access to it.
19. Singleton
Ensure a class only has one instance, and provide a global point of access to it.
20. State
Allow an object to alter its behavior when its internal state changes. The object will
appear to change its class.
21. Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable.
Strategy lets the algorithm vary independently from clients that use it.
22. Template Method
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
Template Method lets subclasses redefine certain steps of an algorithm without changing
the algorithm's structure.
23. Visitor
Represent an operation to be performed on the elements of an object structure. Visitor
lets you define a new operation without changing the classes of the elements on which it
operates.
2.5 Organizing the Catalog
Design patterns vary in their granularity and level of abstraction. Because there are many
design patterns, we need a way to organize them. With this classification of design patterns
we can easily identify related patterns. The classification helps you learn the patterns in the
catalog faster, and it can direct efforts to find new patterns as well.
We classify design patterns by two criteria:
1) Purpose: reflects what a pattern does.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 47


 Patterns can have either creational, structural, or behavioral purpose.
 Creational patterns concern the process of object creation.
 Structural patterns deal with the composition of classes or objects.
 Behavioral patterns characterize the ways in which classes or objects interact and
distribute responsibility.

Table 1.1:Design pattern space


2) Scope: specifies whether the pattern applies primarily to classes or to objects.
Class patterns deal with relationships between classes and their subclasses. These
relationships are established through inheritance, so they are static-fixed at compile-time.

Object patterns deal with object relationships, which can be changed at run-time
and are more dynamic.

So the only patterns labeled "class patterns" are those that focus on class relationships.
Note that most patterns are in the Object scope.
 Creational class patterns defer some part of object creation to subclasses, while
Creational object patterns defer it to another object.
 The Structural class patterns use inheritance to compose classes, while the
Structural object patterns describe ways to assemble objects.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 48


 The Behavioral class patterns use inheritance to describe algorithms and flow of
control, whereas the Behavioral object patterns describe how a group of objects
cooperate to perform a task that no single object can carry out alone.

There are other ways to organize the patterns.


a) Some patterns are often used together: Composite is often used with Iterator or
Visitor.
b) Some patterns are alternatives: Prototype is often an alternative to Abstract Factory.
c) Some patterns result in similar designs even though the patterns have different intents:
the structure diagrams of Composite and Decorator are similar.

Yet another way to organize design patterns is according to how they reference each
other in their "Related Patterns" sections. Clearly there are many ways to organize design
patterns. Having multiple ways of thinking about patterns will deepen your insight
into what they do, how they compare, and when to apply them.

2.6 How to Select a Design Pattern


With more than 20 design patterns in the catalog to choose from, it might be hard
to find the one that addresses a particular design problem, especially if the catalog is new and
unfamiliar to you. Here are several different approaches to finding the design pattern that's right
for your problem:
1) Consider how design patterns solve design problems.
Discussions about how design patterns help you find appropriate objects, determine
object granularity, specify object interfaces, and several other ways in which design patterns
solve design problems. Referring to these discussions can help guide your search for the
right pattern.
2) Scan Intent sections.
Read through each pattern's intent to find one or more that are relevant to your problem.
You can use the classification scheme to reduce your search.
3) Study how patterns interrelate.
Studying the relationships between design patterns can help you to select right pattern or
group of patterns.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 49


4) Study patterns of like purpose.
Each pattern concludes with a section that compares and contrasts with other patterns.
These sections help you to identify the similarities and differences between patterns of like
purpose.
5) Examine a cause of redesign.
Study the causes of redesign to see if your problem involves one or more of them.
Then look at the patterns that help you avoid the causes of redesign.
6) Consider what should be variable in your design.
This approach is the opposite of focusing on the causes of redesign. Instead of
considering what might force a change to a design, consider what you want to be able to
change without redesign. The focus here is on encapsulating the concept that varies, a theme
of many design patterns.

Purpose Design Pattern Aspect(s)That Can Vary


Creational AbstractFactory families of product objects
Builder How a composite object gets created
Factory Method subclass of object that is instantiated
Prototype class of object that is instantiated
Singleton The sole instance of a class
Structural Adapter interface to an object
Bridge implementation of an object
Composite structure and composition of an object
Decorator Responsibilities of an object without subclassing
Facade interface to a subsystem
Flyweight storage costs of objects
Proxy How an object is accessed; its location
Behavioral Chain of Object that can fulfill a request
Responsibility
Command when and how a request is fulfilled
Interpreter grammar and interpretation of a language
Iterator how an aggregate's elements are accessed,

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 50


traversed
Mediator how and which objects interact with each other
Memento what private information is stored outside an
object, and when
Observer number of objects that depend on another object;
how the dependent objects stay up to date
State States of an object
Strategy an algorithm
TemplateMethod steps of an algorithm
Visitor operations that can be applied to object(s)
without changing their class(es)

Table1.2: Design aspects that design patterns let you vary

2.7 How to Use a Design Pattern


Once you've picked a design pattern, how do you use it? Here's a step-by-step approach to
applying a design pattern effectively:
1. Read the pattern once through for an overview. Pay particular attention to the
Applicability and Consequences sections to ensure the pattern is right for your problem.
2. Study the Structure, Participants, and Collaborations sections. Make sure you understand
the classes and objects in the pattern and how they relate to one another.
3. Look at the Sample Code section to see a concrete example of the pattern in code.
Studying the code helps you learn how to implement the pattern.
4. Choose names for pattern participants that are meaningful in the application context. The
names for participants in design patterns are usually too abstract to appear directly in an
application. Nevertheless, it's useful to incorporate the participant name into the name
that appears in the application. That helps make the pattern more explicit in the
implementation.
5. Define the classes. Declare their interfaces, establish their inheritance relationships, and
define the instance variables that represent data and object references. Identify existing
classes in your application that the pattern will affect, and modify them accordingly.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 51


6. Define application-specific names for operations in the pattern. Here again, the names
generally depend on the application. Use the responsibilities and collaborations
associated with each operation as a guide. Also, be consistent in your naming
conventions. For example, you might use the "Create-"prefix consistently to denote a
factory method.
7. Implement the operations to carry out the responsibilities and collaborations in the
pattern. The Implementation section offers hints to guide you in the implementation.
The examples in the Sample Code section can help as well.

2.8 Creational Patterns


Creational design patterns abstract the instantiation process. They help make a system
independent of how its objects are created, composed, and represented. A class creational
pattern uses inheritance to vary the class that's instantiated, whereas an object creational
pattern will delegate instantiation to another object.
Creational patterns become important as systems evolve to depend more on object
composition than class inheritance.
There are two recurring themes in these patterns.
 They all encapsulate knowledge about which concrete classes the system uses.
 They hide how instances of these classes are created and put together.

2.9 AbstractFactory:
Intent:
Provide an interface for creating families of related or dependent objects without
specifying their concrete classes.
Also Known As: Kit
Motivation:
Consider a user interface toolkit that supports multiple look-and-feel standards,
such as Motif and Presentation Manager. Different look-and-feels define different
appearances and behaviors for user interface "widgets" like scroll bars, windows, and
buttons. To be portable across look-and-feel standards, an application should not hard-code
its widgets for a particular look and feel. Instantiating look-and-feel-specific classes of
widgets throughout the application makes it hard to change the look and feel later.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 52


We can solve this problem by defining an abstract WidgetFactory class that
declares an interface for creating each basic kind of widget. There's also an abstract class for
each kind of widget, and concrete subclasses implement widgets for specific look-and-feel
standards. WidgetFactory's interface has an operation that returns a new widget object for
each abstract widget class. Clients call these operations to obtain widget instances, but clients
aren't aware of the concrete classes they're using. Thus clients stay independent of the usual
look and feel.

There is a concrete subclass of WidgetFactory for each look-and-feel standard. Each


subclass implements the operations to create the appropriate widget for the look and
feel. For example, the CreateScrollBar operation on the MotifWidgetFactory instantiates
and returns a Motif scrollbar, while the corresponding operation on the PMWidgetFactory
returns a scroll bar for Presentation Manager. Clients create widgets solely through the
WidgetFactory interface and have no knowledge of the classes that implement widgets for
a particular look and feel.

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.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 53


 A family of related product objects is designed to be used together, and we need to
enforce this constraint.
 We want to provide a class library of products, and you want to reveal just their
interfaces, not their implementations.
Structure:

Participants:
 AbstractFactory (WidgetFactory)
o Declares an interface for operations that create abstract product objects.
 ConcreteFactory (MotifWidgetFactory, PMWidgetFactory)
o Implements the operations to create concrete product objects.
 AbstractProduct (Window, ScrollBar)
o Declares an interface for a type of product object.
 ConcreteProduct (MotifWindow,MotifScrollBar)
o Defines a product object to be created by the corresponding concrete
factory.
o Implements the AbstractProduct interface.
 Client
o Usesonly interfaces declared by AbstractFactory and AbstractProduct
classes.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 54


Collaborations:
 Normally a single instance of a ConcreteFactory class is created at run-time. This
concrete factory creates product objects having a particular implementation. To create
different product objects, clients should use a different concrete factory.
 AbstractFactory defers creation of product objects to its ConcreteFactory subclass.

Consequences:
The AbstractFactory pattern has the following benefits and liabilities:
1. It isolates concrete classes.
2. It makes exchanging product families easy.
3. It promotes consistency among products.
4. Supporting new kinds of products is difficult.

Implementation:
Here are some useful techniques for implementing the Abstract Factory pattern.
1. Factories as singletons.
2. Creating the products.
3. Defining extensible factories.
Sample Code:
ClassMazeFactory can create components of mazes. It builds rooms, walls, and doors
between rooms. It might be used by a program that reads plans for mazes from a file
and builds the corresponding maze. Or it might be used by a program that builds
mazes randomly. Programs that build mazes take a MazeFactory as an argument so
that the programmer can specify the classes of rooms, walls, and doors to
construct.
classMazeFactory {
public:
MazeFactory();
virtual Maze* MakeMaze() const
{ return new Maze; }
virtual Wall* MakeWall() const
{ return new Wall; }

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 55


virtual Room* MakeRoom(int n) const
{ return new Room(n); }
virtual Door* MakeDoor(Room* r1, Room* r2) const
{ return new Door(r1, r2); }
};

Known Uses:
InterViewsuses the "Kit" suffix to denote AbstractFactory classes. It defines
WidgetKit and DialogKit abstract factories for generating look-and-feel-specific user
interface objects. InterViews also includes a LayoutKit that generates different
composition objects depending on the layout desired.

ET++uses the Abstract Factory pattern to achieve portability across different window
systems.

Related Patterns:
AbstractFactory classes are often implemented with factory methods
(FactoryMethod), but they can also be implemented using Prototype.
A concrete factory is often a singleton (Singleton).

2.10 Builder:
Intent:
Separate the construction of a complex object from its representation so that the same
construction process can create different representations.
Motivation:
A reader for the RTF document exchange format should be able to convert RTF to many
text formats. The reader might convert RTF documents into plain ASCII text or into a text
widget that can be edited interactively. The problem, however, is that the number of possible
conversions is open-ended. So it should be easy to add a new conversion without modifying
the reader.
A solution is to configure the RTFReader class with a TextConverter object that converts
RTF to another textual representation. As the RTFReader parses the RTFdocument, it uses
the TextConverter to perform the conversion. Whenever the RTFReader recognizes an RTF

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 56


token, it issues a request to the TextConverter to convert the token. TextConverter objects are
responsible both for performing the data conversion and for representing the token in a
particular format.

Subclasses of TextConverter specialize in different conversions and formats. Each kind


of converter class takes the mechanism for creating and assembling a complex object and
puts it behind an abstract interface. The converter is separate from the reader, which is
responsible for parsing an RTF document.

The Builder pattern captures all these relationships. Each converter class is called a
builder in the pattern, and the reader is called the director.

Applicability:
Use the Builder pattern when
 The algorithm for creating a complex object should be independent of the parts that
make up the object and how they're assembled.
 The construction process must allow different representations for theobject that's
constructed.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 57


Structure:

Participants:
 Builder (TextConverter)
o Specifies an abstract interface for creating parts of a Product object.
 ConcreteBuilder (ASCIIConverter, TeXConverter, TextWidgetConverter)
o Constructs and assembles parts of the product by implementing the Builder
interface.
o Defines and keeps track of the representation it creates.
o Provides an interface for retrieving the product (e.g., GetASCIIText,
GetTextWidget).
 Director (RTFReader)
o Constructs an object using the Builder interface.
 Product (ASCIIText, TeXText, TextWidget)
o Represents the complex object under construction. ConcreteBuilder builds the
product's internal representation and defines the process by which it's
assembled.
o Includes classes that define the constituent parts, including interfaces for
assembling the parts into the final result.

Collaborations:
 The client creates the Director object and configures it with the desired Builder
object.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 58


 Director notifies the builder whenever a part of the product should be built.
 Builder handles requests from the director and adds parts to the product.
 The client retrieves the product from the builder.

Consequences:
Here are key consequences of the Builder pattern:
1. It lets you vary a product's internal representation.
2. It isolates code for construction and representation.
3. It gives you finer control over the construction process.

Implementation:
Typically there's an abstract Builder class that defines an operation for each component
that a director may ask it to create.
Here are other implementation issues to consider:
1. Assembly and construction interface.
2. Why no abstract class for products?
3. Empty methods as default in Builder.
Sample Code:
We'll define a variant of the CreateMaze member function that takes a builder of class
MazeBuilder as an argument.
classMazeBuilder {
public:
virtual void BuildMaze() { }
virtual void BuildRoom(int room) { }
virtual void BuildDoor(int roomFrom, int roomTo) { }
virtual Maze* GetMaze() { return 0; }
protected:
MazeBuilder();
};
This interface can create three things: (1) the maze, (2) rooms with a particular room
number, and (3) doors between numbered rooms. The GetMaze operation returns the maze to

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 59


the client. Subclasses of MazeBuilder will override this operation to return the maze that they
build.

Known Uses:
The RTF converter application is from ET++. Its text building block uses a builder to
process text stored in the RTF format.
Builder is a common pattern in Smalltalk-80:
 The Parser class in the compiler subsystem is a Director that takes a
ProgramNodeBuilder object as an argument.
 ClassBuilder is a builder that Classes use to create subclasses for themselves. In
this case a Class is both the Director and the Product.
 ByteCodeStream is a builder that creates a compiled method as a byte array.
ByteCodeStream is a nonstandard use of the Builder pattern, because the complex
object it builds is encoded as a byte array, not as a normal Smalltalk object.

Related Patterns:
Abstract Factory is similar to Builder in that it too may construct complex objects. The
primary difference is that the Builder pattern focuses on constructing a complex object step
by step. Abstract Factory's emphasis is on families of product objects (either simple or
complex). Builder returns the product as a final step, but as far as the Abstract Factory
pattern is concerned, the product gets returned immediately.
A Composite is what the builder often builds.

2.11 Factory Method


Intent:
Define an interface for creating an object, but let subclasses decide which classto
instantiate. Factory Method lets a class defer instantiation to subclasses.
Also Known As: Virtual Constructor
Motivation:
Frameworks use abstract classes to define and maintain relationships between objects. A
framework is often responsible for creating these objects as well. Consider a framework for

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 60


applications that can present multiple documents to the user. Two key abstractions in this
framework are the classes Application and Document.
This creates a dilemma: The framework must instantiate classes, but it only knows about
abstract classes, which it cannot instantiate.
The Factory Method pattern offers a solution. It encapsulates the knowledge of which
Document subclass to create and moves this knowledge out of the framework.

Application subclasses redefine an abstract CreateDocument operation on Application


to return the appropriate Document subclass. Once an Application subclass is instantiated, it
can then instantiate application-specific Documents without knowing their class. We call
CreateDocument a factory method because it's responsible for "manufacturing" an object.

Applicability:
Use the Factory Method pattern when
 A class can't expect the class of objects it must create.
 A class wants its subclasses to specify the objects it creates.
 Classes delegate responsibility to one of several helper subclasses, and you want to
localize the knowledge of which helper subclass is the delegate.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 61


Structure:

Participants:
 Product (Document)
o Defines the interface of objects the factory method creates.
 ConcreteProduct(MyDocument)
o Implements the Product interface.
 Creator (Application)
o Declares the factory method, which returns an object of type Product.
o Creator may also define a default implementation of the factory method that
returns a default ConcreteProduct object.
o May call the factory method to create a Product object.
 ConcreteCreator(MyApplication)
o Overrides the factory method to return an instance of a ConcreteProduct.

Collaborations:
Creator relies on its subclasses to define the factory method so that it returns an instance
of the appropriate ConcreteProduct.

Consequences:
Factory methods eliminate the need to bind application-specific classes into our code.
The code only deals with the Product interface; therefore it can work with any user-defined
ConcreteProductclasses.

A potential disadvantage of factory methods is that clients might have to subclass the
Creator class just to create a particular ConcreteProduct object.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 62


Here are two additional consequences of the Factory Method pattern:
1. Provides hooks for subclasses.
2. Connects parallel class hierarchies.

Implementation:
Consider the following issues when applying the FactoryMethodpattern:
1. Two major varieties. (1) the case when the Creator class is an abstract class and does
not provide an implementation for the factory method it declares, and (2) the case
when the Creator is a concrete class and provides a default implementation for the
factory method.
2. Parameterized factory methods. Another variation on the pattern lets the factory
method create multiple kinds of products. The factory method takes a parameter that
identifies the kind of object to create. All objects the factory method creates will
share the Product interface.
3. Language-specific variants and issues. Different languages lend themselves to other
interesting variations and requirements.
4. Using templates to avoid subclassing. Another potential problem with factory
methods is that they might force you to subclass just to create the appropriate Product
objects. Another way to get around this in C++ is to provide a template subclass of
Creator that's parameterized by the Product class.
5. Naming conventions. It's good practice to use naming conventions that make it clear
you're using factory methods.

Sample Code:
The function CreateMaze builds and returns a maze. One problem with this function is
that it hard-codes the classes of maze, rooms, doors, and walls. We'll introduce factory
methods to let subclasses choose these components.

First we'll define factory methods in MazeGame for creating the maze, room, wall, and
door objects:
class MazeGame {
public:

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 63


Maze* CreateMaze();
// factory methods:
virtual Maze* MakeMaze() const
{ return new Maze; }
virtual Room* MakeRoom(int n) const
{ return new Room(n); }
virtual Wall* MakeWall() const
{ return new Wall; }
{ return new Door(r1, r2); }
};

Known Uses:
Factory methods provide toolkits and frameworks. The preceding document example is a
typical use in MacApp and ET++. The manipulator example is from Unidraw.

ClassView in the Smalltalk-80 Model/View/Controller framework has a method default


Controller that creates a controller, and this might appear to be a factory method.

Another example in Smalltalk-80 is the factory method parser Class defined by Behavior
(a super class of all objects representing classes).This enables a class to use a customized
parser for its source code.

The Orbix ORB system from IONA Technologies uses Factory Method to generate an
appropriate type of proxy when an object requests a reference to a remote object.

Related Patterns:
Abstract Factory is often implemented with factory methods. Factory methods are usually
called within Template Methods. Prototypes don't require subclassing Creator. However,
they often require an Initialize operation on the Product class. Creator uses Initialize to
initialize the object.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 64


2.12 Prototype
Intent:
Specify the kinds of objects to create using a prototypical instance, and create new
objects by copying this prototype.
Motivation:
We could build an editor for music scores by customizing a general framework for
graphical editors and adding new objects that represent notes, rests, and staves. The editor
framework may have a palette of tools for adding these music objects to the score.

Let's assume the framework provides an abstract Graphic class for graphical components,
like notes and staves. It'll provide an abstract Tool class for defining tools like those in the
palette. The framework also predefines aGraphicTool subclass for tools that create instances
of graphical objects and add them to the document.

But GraphicTool presents a problem to the framework designer. The classes for notes and
staves are specific to our application, but the GraphicTool class belongs to the framework.
GraphicTool doesn't know how to create instances of our music classes to add to the score.
We could subclass GraphicTool for each kind of music object, but that would produce lots
of subclasses that differ only in the kind of music object they instantiate.

The solution lies in making GraphicTool create a new Graphic by copying or "cloning"
an instance of a Graphic subclass. We call this instance a prototype. GraphicToolis
parameterized by the prototype it should clone and add to the document. If all Graphic
subclasses support a Clone operation, then the GraphicTool can clone any kind of Graphic.

So in our music editor, each tool for creating a music object is an instance of
GraphicTool that's initialized with a different prototype. Each GraphicTool instance will
produce a music object by cloning its prototype and adding the clone to the score.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 65


A tool for creating whole notes becomes just a GraphicTool whose prototype is a
MusicalNote initialized to be a whole note. This can reduce the number of classes in the
system dramatically. It also makes it easier to add a new kind of note to the music editor.

Applicability:
Use the Prototype pattern when a system should be independent of how its products are
created, composed, and represented; and
 when the classes to instantiate are specified at run-time, for example, by dynamic
loading; or
 to avoid building a class hierarchy of factories that parallels the class hierarchy of
products; or
 when instances of a class can have one of only a few different combinations of state.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 66


Structure:

Participants:
 Prototype (Graphic)
o Declares an interface for cloning itself.
 ConcretePrototype (Staff, WholeNote, HalfNote)
o Implements an operation for cloning itself.
 Client (GraphicTool)
o Creates a new object by asking a prototype to clone itself.

Collaborations:
 A client asks a prototype to clone itself.

Consequences:
Prototype has many of the same consequences that Abstract Factory and Builder have:
It hides the concrete product classes from the client, thereby reducing the number of
names clients know about. Moreover, these patterns let a client work with application-
specific classes without modification.

Additional benefits of the Prototype pattern are listed below.


1. Adding and removing products at run-time.
2. Specifying new objects by varying values.
3. Specifying new objects by varying structure.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 67


4. Reduced subclassing.
5. Configuring an application with classes dynamically.

Implementation:
Consider the following issues when implementing prototypes:
1. Using a prototype manager. When the number of prototypes in a system isn't
fixed (that is, they can be created and destroyed dynamically), keep a registry of
available prototypes. Clients won't manage prototypes themselves but will store
and retrieve them from the registry. A client will ask the registry for a prototype
before cloning it. We call this registry a prototype manager.
2. Implementing the Clone operation. The hardest part of the Prototype pattern is
implementing the Clone operation correctly.
3. Initializing clones. While some clients are perfectly happy with the clone as is,
others will want to initialize some or all of its internal state to values of their
choosing.

Sample Code:
We'll define a MazePrototypeFactory subclass of the MazeFactory class.
MazePrototypeFactory will be initialized with prototypes of the objects it will create so
that we don't have to subclass it just to change the classes of walls or rooms it creates.

MazePrototypeFactory augments the MazeFactory interface with a constructor that


takes the prototypes as arguments:
class MazePrototypeFactory : public MazeFactory {
public:
MazePrototypeFactory(Maze*, Wall*, Room*, Door*);
virtual Maze* MakeMaze() const;
virtual Room* MakeRoom(int) const;
virtual Wall* MakeWall() const;
virtual Door* MakeDoor(Room*, Room*) const;
private:
Maze* _prototypeMaze;

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 68


Room* _prototypeRoom;
Wall* _prototypeWall;
Door* _prototypeDoor;
};

Known Uses:
Perhaps the first example of the Prototype pattern was in Ivan Sutherland's Sketchpad
system. The first widely known application of the pattern in an object-oriented language
was in ThingLab.

Etgdb is a debugger front-end based on ET++ that provides a point-and-click


interface to different line-oriented debuggers. Each debugger has a corresponding
DebuggerAdaptor subclass.

The "interaction technique library" in Mode Composer stores prototypes of objects


that support various interaction techniques. The music editor example discussed earlier is
based on the Unidraw drawing framework

Related Patterns:
 Prototype and Abstract Factory are competing patterns in some ways. However,
they can also be used together.
 An Abstract Factory might store a set of prototypes from which to clone and
return product objects.
 Designs that make heavy use of the Composite and Decorator patterns often can
benefit from Prototype as well.

2.13 Singleton:
Intent:
Ensure a class only has one instance, and provide a global point of access toit.
Motivation:
It's important for some classes to have exactly one instance. Examples:
 Although there can be many printers in a system, there should be only one
printer spooler.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 69


 There should be only one file system and one window manager.
 A digital filter will have one A/D converter.
 An accounting system will be dedicated to serving one company.

How do we ensure that a class has only one instance and that the instance is easily
accessible? A global variable makes an object accessible, but it doesn't keep you from
instantiating multiple objects.

A better solution is to make the class itself responsible for keeping track of its sole
instance. The class can ensure that no other instance can be created, and it can provide a
way to access the instance. This is the Singleton pattern.

Applicability:
Use the Singleton pattern when
 there must be exactly one instance of a class, and it must be accessible to
clients from a well-known access point.
 when the sole instance should be extensible by subclassing, and clients should
be able to use an extended instance without modifying their code.
Structure:

Participants:
 Singleton
o Defines an Instance operation that lets clients access its unique instance.
Instance is a class operation.
o May be responsible for creating its own unique instance.
Collaborations:
Clients access a Singleton instance solely through Singleton's Instance operation.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 70


Consequences:
The Singleton pattern has several benefits:
1. Controlled access to sole instance. Because the Singleton class encapsulates its
sole instance, it can have strict control over how and when clients access it.
2. Reduced name space. The Singleton pattern is an improvement over global
variables. It avoids polluting the name space with global variables that store sole
instances.
3. Permits refinement of operations and representation. We can configure the
application with an instance of the class we need at run-time.
4. Permits a variable number of instances. The pattern makes it easy to change your
mind and allow more than one instance of the Singleton class.
5. More flexible than class operations. Another way to package a singleton's
functionality is to use class operations.

Implementation:
Here are implementation issues to consider when using the Singleton pattern:
1. Ensuring a unique instance. The Singleton pattern makes the sole instance a
normal instance of a class, but that class is written so that only one instance can
ever be created. A common way to do this is to hide the operation that creates the
instance behind a class operation that guarantees only one instance is created.
2. Subclassing the Singleton class. The main issue is not so much defining the
subclass but installing its unique instance so that clients will be able to use it. The
simplest technique is to determine which singleton you want to use in the
Singleton's Instance operation.
Another way to choose the subclass of Singleton is to take the implementation
of Instance out of the parent class and put it in the subclass.
A more flexible approach uses a registry of singletons. Instead of having
Instance define the set of possible Singleton classes, the Singleton classes can
register their singleton instance by name in a well-known registry. This approach
frees Instance from knowing all possible Singleton classes or instances.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 71


Sample Code:
MazeFactory defines an interface for building different parts of a maze. Subclasses
can redefine the operations to return instances of specialized product classes, like
BombedWall objects instead of plain Wall objects.
class MazeFactory {
public:
static MazeFactory* Instance();
// existing interface goes here
protected:
MazeFactory();
private:
static MazeFactory* _instance;
};
The corresponding implementation is
MazeFactory* MazeFactory::_instance = 0;
MazeFactory* MazeFactory::Instance () {
if (_instance == 0) {
_instance = new MazeFactory;
}
return _instance;
}

Known Uses:
An example of the Singleton pattern in Smalltalk-80is the set of changes to the code,
which is ChangeSet current. A more subtle example is the relationship between classes
and their meta classes.
The InterViews user interface toolkit uses the Singleton pattern to access the unique
instance of its Session and WidgetKit classes, among others.

Related Patterns:
Many patterns can be implemented using the Singleton pattern: AbstractFactory,
Builder, and Prototype.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 72


2.14 Discussion of Creational Patterns
There are two common ways to parameterize a system by the classes of objects it creates.
1. Subclass the class that creates the objects; this corresponds to using the Factory
Method pattern. The main drawback of this approach is that it can require creating a
new subclass just to change the class of the product. Such changes can cascade.
2. The other way to parameterize a system relies more on object composition: Define
an object that's responsible for knowing the class of the product objects, and make it
a parameter of the system. This is a key aspect of the Abstract Factory, Builder, and
Prototype patterns.

All three involve creating a new "factory object" whose responsibility is to create
product objects.
 Abstract Factory has the factory object producing objects of several classes.
 Builder has the factory object building a complex product incrementally using a
correspondingly complex protocol.
 Prototype has the factory object building a product by copying a prototype object.
 In this case, the factory object and the prototype are the same object, because the
prototype is responsible for returning the product.

Consider the drawing editor framework described in the Prototype pattern. There are
several ways to parameterize a GraphicTool by the class of product:
 By applying the Factory Method pattern, a subclass of GraphicTool will be created
for each subclass of Graphic in the palette. GraphicTool will have a NewGraphic
operation that each GraphicTool subclass will redefine.
 By applying the Abstract Factory pattern, there will be a class hierarchy of
GraphicsFactories, one for each Graphic subclass. Each factory creates just one
product in this case: CircleFactory will create Circles, LineFactory will create
Lines, and so on. A GraphicTool will be parameterized with a factory for creating
the appropriate kind of Graphics.
 By applying the Prototype pattern, each subclass of Graphics will implement the
Clone operation, and a GraphicTool will be parameterized with a prototype of the
Graphic it creates.
P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 73
Which pattern is best depends on many factors.
 In our drawing editor framework, the Factory Method pattern is easiest to use at
first.
 Abstract Factory doesn't offer much of an improvement, because it requires an
equally large GraphicsFactory class hierarchy.
 Overall, the Prototype pattern is probably the best for the drawing editor
framework, because it only requires implementing a Clone operation on each
Graphics class. That reduces the number of classes, and Clone can be used for
purposes other than pure instantiation.
 Factory Method makes a design more customizable and only a little more
complicated.
 Other design patterns require new classes, whereas Factory Method only requires
a new operation.
 Designs that use Abstract Factory, Prototype, or Builder are even more flexible
than those that use Factory Method, but they're also more complex.
 Knowing many design patterns gives you more choices when trading off one
design criterion against another.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 74


UNIT -III

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 75


UNIT-3
Structural Patterns

Introduction:
 Structural patterns are concerned with how classes and objects are composed to form
larger structures.
 Structural class patterns use inheritance to compose interfaces or implementations.
 Example: The class form of the Adapter pattern.
 In general, an adapter makes one interface (the adaptee's) conform to another,
thereby providing a uniform abstraction of different interfaces.
 A class adapter accomplishes this by inheriting privately from an adaptee class.
 The adapter then expresses its interface in terms of the adaptee's.
 Rather than composing interfaces or implementations, structural object patterns
describe ways to compose objects to realize new functionality.
 The object composition becomes flexible due to the ability to change the composition at
run-time, which is impossible with static class composition.
 Example: Composite pattern.
 How to build a class hierarchy made up of classes for two kinds of objects:
primitive and composite.
 The composite objects let you compose primitive and other composite objects into
arbitrarily complex structures.
3.1Adapter:
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 class that's designed for reuse isn't reusable only because its
interface doesn't match the domain-specific interface an application requires.
 Consider for example a drawing editor that lets users draw and arrange graphical
elements (lines, polygons, text, etc.) into pictures and diagrams.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 76


 The interface for graphical objects is defined by an abstract class called Shape.
 The editor defines a subclass of Shape for each kind of graphical object.
 Classes for elementary geometric shapes are easy to implement. But a TextShape
subclass that can display and edit text is more difficult to implement. (screen updates,
buffer updates)
 How can existing and unrelated classes like TextView work in an application that
expects classes with a different and incompatible interface?
 We could define TextShape so that it adapts the TextView interface to Shape's.
(1) by inheriting Shape's interface and TextView's implementation or
(2) by composing a TextView instance within a TextShape and implementing
TextShape in terms of TextView's interface.

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 or unforeseen classes,
that is, classes that don't necessarily have compatible interfaces.
 (object adapter only) you need to use several existing subclasses, but it's impractical to
adapt their interface by subclassing every one. An object adapter can adapt the
interface of its parent class.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 77


Structure:
Class adapter

Object adapter

Participants:
 Target (Shape)
 defines the domain-specific interface that Client uses.
 Client (DrawingEditor)
 collaborates with objects conforming to the Target interface.
 Adaptee (TextView)
 defines an existing interface that needs adapting.
 Adapter (TextShape)

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 78


 adapts the interface of Adaptee to the Target interface.
Collaborations:
Clients call operations on an Adapter instance. In turn, the adapter calls Adaptee
operations that carry out the request.
Consequences:
Class and object adapters have different trade-offs. A class adapter
 adapts Adaptee to Target by committing to a concrete Adapter class.
 lets Adapter override some of Adaptee's behavior, since Adapter is a subclass of
Adaptee.
 introduces only one object, and no additional pointer indirection is needed to get to
the adaptee.
An object adapter
 lets a single Adapter work with many Adaptees
 makes it harder to override Adaptee behavior.
Here are other issues to consider when using the Adapter pattern:
 How much adapting does Adapter do?
 Pluggable adapters: describe classes with built-in interface adaptation.
 Using two-way adapters to provide transparency.

Implementation:
Here are some issues to keep in mind while implementing Adapter:
1. Implementing class adapters in C++. Adapter would inherit publicly from Target and
privately from Adaptee.
2. Pluggable adapters.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 79


 find a "narrow" interface for Adaptee
The narrow interface leads to three implementation approaches:
a. Using abstract operations.
b. Using delegate objects.
c. Parameterized adapters.
Sample Code:
class Shape {
public:
Shape();
virtual void BoundingBox(Point& bottomLeft, Point& topRight) const;
virtual Manipulator* CreateManipulator() const;};
class TextView {
public:
TextView();
voidGetOrigin(Coord& x, Coord& y) const;
voidGetExtent(Coord& width, Coord& height) const;
virtual bool IsEmpty() const;
};
class TextShape : public Shape, private TextView {
public:
TextShape();
virtual void BoundingBox(Point& bottomLeft, Point& topRight) const;
virtual bool IsEmpty() const;
virtual Manipulator* CreateManipulator() const;};
Known Uses:
This pattern is used in the following toolkits: ET++Draw, InterViews 2.6,
ObjectWorks\Smalltalk, NeXT'sAppKit
Related Patterns:
 Bridge: has same structure but different intent.
 Decorator: enhances another object without changing its interface.
 Proxy: representative or surrogate for another object and does not change its interface.
 Factory Method is also a related pattern.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 80


3.2 Bridge:
Intent:
Decouple an abstraction from its implementation so that the two can vary independently.
Also Known As: Handle/Body
Motivation:
 When an abstraction can have one of several possible implementations, the usual way
to accommodate them is to use inheritance.
 An abstract class defines the interface to the abstraction, and concrete subclasses
implement it in different ways.
 But this approach isn't always flexible enough.

 But this approach has two drawbacks:


 It's inconvenient to extend the Window abstraction to cover different kinds of
windows or new platforms.
 It makes client code platform-dependent.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 81


Applicability:
Use the Bridge pattern when
 you want to avoid a permanent binding between an abstraction and its
implementation.
 both the abstractions and their implementations should be extensible by
subclassing.
 changes in the implementation of an abstraction should have no impact on clients;
 (C++) you want to hide the implementation of an abstraction completely from
clients.
 you have a proliferation of classes as shown earlier in the first Motivation diagram.
 you want to share an implementation among multiple objects, and this fact should
be hidden from the client.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 82


Structure:

Participants:
 Abstraction (Window)
 defines the abstraction's interface.
 maintains a reference to an object of type Implementor.
 RefinedAbstraction (IconWindow)
 Extends the interface defined by Abstraction.
 Implementor (WindowImp)
 defines the interface for implementation classes. Typically the Implementor
interface provides only primitive operations, and Abstraction defines higher-
level operations based on these primitives.
 ConcreteImplementor (XWindowImp, PMWindowImp)
 implements the Implementor interface and defines its concrete implementation.
Collaborations:
 Abstraction forwards client requests to its Implementor object.

Consequences:
The Bridge pattern has the following consequences:
1. Decoupling interface and implementation.
 Decoupling Abstraction and Implementor also eliminates compile-time
dependencies on the implementation.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 83


2. Improved extensibility.
 You can extend the Abstraction and Implementor hierarchies independently.
3. Hiding implementation details from clients.
 You can shield clients from implementation details, like the sharing of
implementor objects and the accompanying reference count mechanism (if any).

Implementation:
Consider the following implementation issues when applying the Bridge pattern:
1. Only one Implementor.
 Useful when a change in the implementation of a class must not affect its existing
clients
2. Creating the right Implementor object.
 How, when, and where do you decide which Implementor class to instantiate
when there's more than one?
3. Sharing implementors.
4. Using multiple inheritance.

Sample Code:
class Window {
public:
Window(View* contents);
// requests handled by window
virtual void DrawContents();
virtual void Open();
virtual void Close();
virtual void Iconify();
virtual void Deiconify();
// requests forwarded to implementation
virtual void SetOrigin(const Point& at);
virtual void SetExtent(const Point& extent);
virtual void Raise();
virtual void Lower();

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 84


virtual void DrawLine(const Point&, const Point&);
virtual void DrawRect(const Point&, const Point&);
virtual void DrawPolygon(const Point[], int n);
virtual void DrawText(const char*, const Point&);
protected:
WindowImp* GetWindowImp();
View* GetView();
private:
WindowImp* _imp;
View* _contents; // the window's contents
};
Known Uses:
 In ET++, WindowImp is called "WindowPort" and has subclasses such as XWindowPort
and SunWindowPort.
 The ET++ Window/WindowPort design extends the Bridge pattern in that the
WindowPort also keeps a reference back to the Window.
 libg++ defines classes that implement common data structures, such as Set, LinkedSet,
HashSet, LinkedList, and HashTable.
 NeXT's AppKit uses the Bridge pattern in the implementation and display of graphical
images.
Related Patterns:
 An Abstract Factory can create and configure a particular Bridge.
 The Adapter pattern is geared toward making unrelated classes work together.

3.3 Composite:
Intent:
Compose objects into tree structures to represent part-whole hierarchies. Composite lets
clients treat individual objects and compositions of objects uniformly.
Motivation:
Graphics applications like drawing editors and schematic capture systems let users
build complex diagrams out of simple components.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 85


Problem:
Code that uses these classes must treat primitive and container objects differently, even if
most of the time the user treats them identically. Having to distinguish these objects makes the
application more complex.
Solution:
The Composite pattern describes how to use recursive composition so that clients don't have to
make this distinction.
 The key to the Composite pattern is an abstract class (Graphic) that represents both
primitives and their containers.
 Graphic declares operations like Draw that are specific to graphical objects.
 It also declares operations that all composite objects share, such as operations for
accessing and managing its children.
 The subclasses Line, Rectangle, and Text define primitive graphical objects.
 Since primitive graphics have no child graphics, none of these subclasses implements
child-related operations.
 The Picture class defines an aggregate of Graphic objects.
 Because the Picture interface conforms to the Graphic interface, Picture objects can
compose other Pictures recursively.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 86


The following diagram shows a typical composite object structure of recursively
composed Graphic objects:

Applicability:
Use the Composite pattern when
 you want to represent part-whole hierarchies of objects.
 you want clients to be able to ignore the difference between compositions of
objects and individual objects. Clients will treat all objects in the composite
structure uniformly.
Structure:

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 87


A typical Composite object structure might look like this:

Participants:
 Component (Graphic)
 declares the interface for objects in the composition.
 implements default behavior for the interface common to all classes, as
appropriate.
 declares an interface for accessing and managing its child components.
 (optional) defines an interface for accessing a component's parent in 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 children.
 defines behavior for primitive objects in the composition.
 Composite (Picture)
 defines behavior for components having children.
 stores child components.
 implements child-related operations in the Component interface.
 Client
 manipulates objects in the composition through the Component interface.
Collaborations:
 Clients use the Component class interface to interact with objects in the
composite structure. If the recipient is a Leaf, then the request is handled
directly. If the recipient is a Composite, then it usually forwards requests to its
child components, possibly performing additional operations before and/or after
forwarding.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 88


Consequences:
The Composite pattern
 defines class hierarchies consisting of primitive objects and composite objects.
 makes the client simple. Clients can treat composite structures and individual objects
uniformly.
 makes it easier to add new kinds of components. Clients don't have to be changed for
new Component classes.
 can make your design overly general. The disadvantage of making it easy to add new
components is that it makes it harder to restrict the components of a composite.
You'll have to use run-time checks instead.

Implementation:
There are many issues to consider when implementing the Composite pattern:
 Explicit parent references.
 Sharing components.
 Maximizing the Component interface.
 Declaring the child management operations.
The decision involves a trade-off between safety and transparency:
 Defining the child management interface at the root of the class hierarchy gives
you transparency.
 Defining child management in the Composite class gives you safety.
 Should Component implement a list of Components?
 Child ordering.
 Caching to improve performance.
 Who should delete components?
 What's the best data structure for storing components? The choice of data structure
depends on efficiency.

Sample Code:
class Equipment {
public:
virtual ~Equipment();

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 89


const char* Name(){ return _name; }
virtual Watt Power();
virtual Currency NetPrice();
virtual Currency DiscountPrice();
virtual void Add(Equipment*);
virtual void Remove(Equipment*);
virtual Iterator* CreateIterator();
protected:
Equipment(const char*);
private:
const char* _name;
};

class FloppyDisk: public Equipment {


public:
FloppyDisk(const char*);
virtual ~FloppyDisk();
virtual Watt Power();
virtual Currency NetPrice();
virtual Currency DiscountPrice();
};

Currency CompositeEquipment::NetPrice () {
Iterator* i = CreateIterator();
Currency total = 0;
for (i->First(); !i->IsDone(); i->Next()) {
total += i->CurrentItem()->NetPrice();
}
delete i;
return total;
}

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 90


class CompositeEquipment : public Equipment {
public:
virtual ~CompositeEquipment();
virtual Watt Power();
virtual Currency NetPrice();
virtual Currency DiscountPrice();
virtual void Add(Equipment*);
virtual void Remove(Equipment*);
virtual Iterator* CreateIterator();
protected:
CompositeEquipment(const char*);
private:
List _equipment;
};

Known Uses:
 The original View class of Smalltalk Model/View/Controller was a Composite, and
nearly every user interface toolkit or framework has followed in its steps, including
ET++ and InterViews, Graphics, and Glyphs.
 The RTL Smalltalk compiler framework uses the Composite pattern extensively.
 Another example of this pattern occurs in the financial domain, where a portfolio
aggregates individual assets.
 The Command pattern describes how Command objects can be composed and
sequenced with a MacroCommand Composite class.
Related Patterns:
 Often the component-parent link is used for a Chain of Responsibility.
 Decorator is often used with Composite.
 Flyweight lets you share components, but they can no longer refer to their parents.
 Iterator can be used to traverse composites.
 Visitor localizes operations and behavior that would otherwise be distributed across
Composite and Leaf classes.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 91


3.4 Decorator:
Intent:
Attach additional responsibilities to an object dynamically. Decorators provide a flexible
alternative to subclassing for extending functionality.
Also Known As: Wrapper
Motivation:
 Sometimes we want to add responsibilities to individual objects, not to an
entire class.
 One way to add responsibilities is with inheritance.
 Inheriting a border from another class puts a border around every subclass instance.
 This is inflexible, a client can't control how and when to decorate the component with a
border.
 A more flexible approach is to enclose the component in another object that
adds the border. The enclosing object is called a decorator.
 The decorator conforms to the interface of the component it decorates so that its
presence is transparent to the component's clients.
 The decorator forwards requests to the component and may perform additional actions
before or after forwarding.
 Transparency lets you nest decorators recursively, thereby allowing an unlimited
number of added responsibilities.

The following object diagram shows how to compose a TextView object with
BorderDecorator and ScrollDecorator objects to produce a bordered, scrollable text view:

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 92


 VisualComponent is the abstract class for visual objects.
 It defines their drawing and event handling interface.
 We can see how the Decorator class simply forwards draw requests to its component,
and how Decorator subclasses can extend this operation.
 Decorator subclasses are free to add operations for specific functionality.

Applicability:
Use Decorator
 to add responsibilities to individual objects dynamically and transparently, that is,
without affecting other objects.
 for responsibilities that can be withdrawn.
 when extension by subclassing is impractical. Sometimes a large number of
independent extensions are possible and would produce an explosion of subclasses to
support every combination. Or a class definition may be hidden or otherwise
unavailable for subclassing.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 93


Structure:

Participants:
 Component (VisualComponent)
 defines the interface for objects that can have responsibilities added to them
dynamically.
 ConcreteComponent (TextView)
 defines an object to which additional responsibilities can be attached.
 Decorator
 maintains a reference to a Component object and defines an interface that
conforms to Component's interface.
 ConcreteDecorator (BorderDecorator, ScrollDecorator)
 adds responsibilities to the component.
Collaborations:
 Decorator forwards requests to its Component object. It may optionally perform
additional operations before and after forwarding the request.
Consequences:
The Decorator pattern has at least two key benefits and two liabilities:
1. More flexibility than static inheritance.
2. Avoids feature-laden classes high up in the hierarchy.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 94


3. A decorator and its component aren't identical.
4. Lots of little objects. (that all look alike)
Implementation:
Several issues should be considered when applying the Decorator pattern:
1. Interface conformance.
2. Omitting the abstract Decorator class.
3. Keeping Component classes lightweight.
4. Changing the skin of an object versus changing its guts.

Sample Code:
class VisualComponent {
public:
VisualComponent();
virtual void Draw();
virtual void Resize();
// ...
};

class Decorator : public VisualComponent {


public:
Decorator(VisualComponent*);

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 95


virtual void Draw();
virtual void Resize();
// ...
private:
VisualComponent* _component;
};
void Decorator::Draw () {
_component->Draw();
}
void Decorator::Resize () {
_component->Resize();
}

class BorderDecorator : public Decorator {


public:
BorderDecorator(VisualComponent*, int borderWidth);
virtual void Draw();
private:
void DrawBorder(int);
private:
int _width;
};

Void BorderDecorator::Draw () {
Decorator::Draw();
DrawBorder(_width);
}

Known Uses:
Many object-oriented user interface toolkits use decorators
Ex. InterViews, ET++, ObjectWorks\Smalltalk class library

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 96


Related Patterns:
Adapter: a decorator only changes an object's responsibilities, not its interface; an adapter
will give an object a completely new interface.
Composite: A decorator can be viewed as a degenerate composite with only one component.
Strategy: A decorator lets you change the skin of an object; a strategy lets you change the
guts. These are two alternative ways of changing an object.

3.5 Facade:
Intent:
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.
Motivation:
 Structuring a system into subsystems helps reduce complexity.
 A common design goal is to minimize the communication and dependencies between
subsystems.
 One way to achieve this goal is to introduce a facade object that provides a single,
simplified interface to the more general facilities of a subsystem.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 97


 The Compiler class acts as a facade: It offers clients a single, simple interface to the
compiler subsystem.
 It joins together the classes that implement compiler functionality without hiding them
completely.
 The compiler facade makes life easier for most programmers without hiding the lower-
level functionality from the few that need it.

Applicability:
Use the Facade pattern when
 you want to provide a simple interface to a complex subsystem.
 there are many dependencies between clients and the implementation classes of an
abstraction.
 you want to layer your subsystems. Use a facade to define an entry point to each
subsystem level.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 98


Structure:

Participants:
 Facade (Compiler)
 Knows which subsystem classes are responsible for a request.
 Delegates client requests to appropriate subsystem objects.
 Subsystem classes (Scanner, Parser, ProgramNode, etc.)
 Implement subsystem functionality.
 handle work assigned by the Facade object.
 have no knowledge of the facade; that is, they keep no references to it.

Collaborations:
 Clients communicate with the subsystem by sending requests to Facade, which
forwards them to the appropriate subsystem object(s). Although the subsystem objects
perform the actual work, the facade may have to do work of its own to translate its
interface to subsystem interfaces.
 Clients that use the facade don't have to access its subsystem objects directly.

Collaborations:
1. It shields clients from subsystem components, thereby reducing the number of objects
that clients deal with and making the subsystem easier to use.
2. It promotes weak coupling between the subsystem and its clients.
3. It doesn't prevent applications from using subsystem classes if they need to. Thus you
can choose between ease of use and generality.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 99


Implementation:
Consider the following issues when implementing a facade:

1. Reducing client-subsystem coupling. Clients that use the facade don't have to access
its subsystem objects directly.
2. Public versus private subsystem classes.

Sample Code :
The Scanner class takes a stream of characters and produces a stream of tokens, one
token at a time.

class Scanner {
public:
Scanner(istream&);
virtual ~Scanner();
virtual Token& Scan();
private:
istream& _inputStream;
};

The class Parser uses a ProgramNodeBuilder to construct a parse tree from a Scanner's
tokens.

class Parser {
public:
Parser();
virtual ~Parser();
virtual void Parse(Scanner&, ProgramNodeBuilder&);
};

Known Uses :
 ObjectWorks\Smalltalk compiler system
 ET++ application framework
 The Choices operating system

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 100


Related Patterns:
 Abstract Factory: It can be used with Facade to provide an interface for creating
subsystem objects in a subsystem-independent way. Abstract Factory can also be used
as an alternative to Façade to hide platform-specific classes.
 Mediator: It is similar to Facade in that it abstracts functionality of existing classes.
 Singleton: Usually only one Facade object is required. Thus Façade objects are often
Singletons.

3.6 Flyweight:
Intent:
Use sharing to support large numbers of fine-grained objects efficiently.
Motivation:
 Some applications could benefit from using objects throughout their design, but a naive
implementation would be prohibitively expensive.
 Example: most document editor implementations have text formatting and editing
facilities that are modularized to some extent.
 Object-oriented document editors typically use objects to represent embedded elements
like tables and figures.
 However, they usually stop short of using an object for each character in the document,
even though doing so would promote flexibility at the finest levels in the application.
 Characters and embedded elements could then be treated uniformly with respect to how
they are drawn and formatted.
 The following fig. shows how a document editor can use objects to represent
characters.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 101


 The drawback of such a design is its cost.
 Even moderate-sized documents may require hundreds of thousands of character objects,
which will consume lots of memory and may incur unacceptable run-time overhead.
 The Flyweight pattern describes how to share objects to allow their use at fine
granularities without prohibitive cost.
 A flyweight is a shared object that can be used in multiple contexts simultaneously.
 Flyweights cannot make assumptions about the context in which they operate.
 The key concept here is the distinction between intrinsic and extrinsic state.
 Intrinsic state is stored in the flyweight; it consists of information that's independent of
the flyweight„s context, thereby making it sharable.
 Extrinsic state depends on & varies with the flyweight's context and therefore can't be
shared.
 Client objects are responsible for passing extrinsic state to the flyweight when it needs it.
 Logically there is an object for every occurrence of a given character in the document:

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 102


Applicability:
Apply the Flyweight pattern when all of the following are true:
 An application uses a large number of objects.
 Storage costs are high because of the sheer quantity of objects.
 Most object state can be made extrinsic.
 Many groups of objects may be replaced by relatively few shared objects once
extrinsic state is removed.
 The application doesn't depend on object identity. Since flyweight objects may be
shared, identity tests will return true for conceptually distinct objects.
Structure:

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 103


The following object diagram shows how flyweights are shared:

Participants:
 Flyweight
 declares an interface through which flyweights can receive and act on
extrinsic state.
 ConcreteFlyweight (Character)
 implements the Flyweight interface and adds storage for intrinsic state, if
any. Its object must be sharable. Any state it stores must be intrinsic; that is, it
must be independent of the ConcreteFlyweight object's context.
 UnsharedConcreteFlyweight(Row, Column)
 not all Flyweight subclasses need to be shared. The Flyweight interface enables
sharing; it doesn‟t enforce it. It's common for UnsharedConcreteFlyweight objects
to have ConcreteFlyweight objects as children at some level in the flyweight
object structure (as the Row and Column classes have).
 FlyweightFactory
 creates and manages flyweight objects.
 ensures that flyweights are shared properly. When a client requests a flyweight,
the FlyweightFactory object supplies an existing instance or creates one, if none
exists.
 Client
 maintains a reference to flyweight(s).
 computes or stores the extrinsic state of flyweight(s).

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 104


Collaborations:
 State that a flyweight needs to function must be characterized as either intrinsic or
extrinsic. Intrinsic state is stored in the ConcreteFlyweight object; extrinsic state is
stored or computed by Client objects. Clients pass this state to the flyweight when they
invoke its operations.
 Clients should not instantiate ConcreteFlyweights directly. Clients must obtain
ConcreteFlyweight objects exclusively from the FlyweightFactory object to ensure they
are shared properly.
Consequences:
 Flyweights may introduce run-time costs associated with transferring, finding, and/or
computing extrinsic state, especially if it was formerly stored as intrinsic state.
 such costs are offset by space savings, which increase as more flyweights are shared.
Storage savings are a function of several factors:
 the reduction in the total number of instances that comes from sharing
 the amount of intrinsic state per object
 whether extrinsic state is computed or stored.
 The Flyweight pattern is often combined with the Composite pattern to represent a
hierarchical structure as a graph with shared leaf nodes. A consequence of sharing is
that flyweight leaf nodes cannot store a pointer to their parent.
Implementation:
Consider the following issues when implementing the Flyweight pattern:
1. Removing extrinsic state.
 The pattern's applicability is determined largely by how easy it is to identify
extrinsic state and remove it from shared objects.
 Removing extrinsic state won't help reduce storage costs if there are as many
different kinds of extrinsic state as there are objects before sharing.
 Ideally, extrinsic state can be computed from a separate object structure, one with
far smaller storage requirements.
2. Managing shared objects.
 Because objects are shared, clients shouldn't instantiate them directly.
 FlyweightFactory lets clients locate a particular flyweight.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 105


 FlyweightFactory objects often use an associative store to let clients lookup
flyweights of interest.
 Sharability also implies some form of reference counting or garbage collection to
reclaim a flyweight's storage when it's no longer needed.
 However, neither is necessary if the number of flyweights is fixed and small.
 In that case, the flyweights are worth keeping around permanently.
Sample Code:
class Glyph {
public:
virtual ~Glyph();
virtual void Draw(Window*, GlyphContext&);
virtual void SetFont(Font*, GlyphContext&);
virtual Font* GetFont(GlyphContext&);
virtual void First(GlyphContext&);
virtual void Next(GlyphContext&);
virtual bool IsDone(GlyphContext&);
virtual Glyph* Current(GlyphContext&);
virtual void Insert(Glyph*, GlyphContext&);
virtual void Remove(GlyphContext&);
protected:
Glyph();
};

The Character subclassjust stores a character code:

class Character : public Glyph {


public:
Character(char);
virtual void Draw(Window*, GlyphContext&);
private:
char _charcode;
};

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 106


class GlyphContext {
public:
GlyphContext();
virtual ~GlyphContext();
virtual void Next(int step = 1);
virtual void Insert(int quantity = 1);
virtual Font* GetFont();
virtual void SetFont(Font*, int span = 1);
private:
int _index;
BTree* _fonts;
};
Known Uses :
 The concept of flyweight objects was first described and explored as a design
technique in InterViews 3.0
 ET++ uses flyweights to support look-and-feel independence.
Related Patterns:
 The Flyweight pattern is often combined with the Composite pattern to implement a
logically hierarchical structure in terms of a directed-acyclic graph with shared leaf
nodes.
 It's often best to implement State and Strategy objects as Flyweights.

3.7 Proxy:
Intent:
Provide a surrogate or placeholder for another object to control access to it.
Also Known As: Surrogate
Motivation:
 One reason for controlling access to an object is to defer the full cost of its
creation and initialization until we actually need to use it.
 These constraints would suggest creating each expensive object on demand.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 107


 Solution: use another object, an image proxy, that acts as a stand-in for the real
image.
 The proxy acts just like the image and takes care of instantiating it when it's
required.

 The image proxy creates the real image only when the document editor asks it to
display itself by invoking its Draw operation.
 The proxy forwards subsequent requests directly to the image. It must therefore
keep a reference to the image after creating it.

 The document editor accesses embedded images through interface defined by the
abstract Graphic class.
 ImageProxy is a class for images that are created on demand. ImageProxy
maintains the file name as a reference to the image on disk.
 The file name is passed as an argument to the ImageProxy constructor.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 108


 ImageProxy also stores the bounding box of the image and a reference to
the real Image instance. This reference won't be valid until the proxy instantiates
the real image.
 The Draw operation makes sure the image is instantiated before forwarding it the
request.
 GetExtent forwards the request to the image only if it's instantiated; otherwise
ImageProxy returns the extent it stores.

Applicability:
 Proxy is applicable whenever there is a need for a more versatile or sophisticated
reference to an object than a simple pointer.
Here are several common situations in which the Proxy pattern is applicable:
1. A remote proxy provides a local representative for an object in a different address space.
NEXTSTEP uses the class NXProxy for this purpose. Coplien calls this kind of proxy an
"Ambassador."
2. A virtual proxy creates expensive objects on demand. The ImageProxy described in the
Motivation is an example of such a proxy.
3. A protection proxy controls access to the original object. Protection proxies are useful
when objects should have different access rights. For example, KernelProxies in the
Choices operating system provide protected access to operating system objects.
4. A smart reference is a replacement for a bare pointer that performs additional actions
when an object is accessed. Typical uses include
 counting the number of references to the real object so that it can be freed
automatically when there are no more references (also called smart-pointers).
 loading a persistent object into memory when it's first referenced.
 checking that the real object is locked before it's accessed to ensure that no other
object can change it.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 109


Structure:

Here's a possible object diagram of a proxy structure at run-time:

Participants:
 Proxy (ImageProxy)
 maintains a reference that lets the proxy access the real subject. Proxy may
refer to a Subject if the RealSubject and Subject interfaces are the same.
 provides an interface identical to Subject's so that a proxy can by substituted
for the real subject.
 controls access to the real subject and may be responsible for creating and
deleting it.
Other responsibilities depend on the kind of proxy:
 remote proxies are responsible for encoding a request and its arguments and for
sending the encoded request to the real subject in a different address space.
 virtual proxies may cache additional information about the real subject so that
they can postpone accessing it. For example, the ImageProxy from the Motivation
caches the real image's extent.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 110


 protection proxies check that the caller has the access permissions required to
perform a request.
 Subject (Graphic)
 defines the common interface for RealSubject and Proxy so that a Proxy can be
used anywhere a RealSubject is expected.
 RealSubject (Image)
 defines the real object that the proxy represents.
Collaborations:
 Proxy forwards requests to RealSubject when appropriate, depending on the kind of
proxy.
Consequences:
 The Proxy pattern introduces a level of indirection when accessing an object.
 The additional indirection has many uses, depending on the kind of proxy:
1. A remote proxy can hide the fact that an object resides in a different address space.
2. A virtual proxy can perform optimizations such as creating an object on demand.
3. Both protection proxies and smart references allow additional housekeeping tasks
when an object is accessed.
 There's another optimization that the Proxy pattern can hide from the client.
 It's called copy-on-write, and it's related to creation on demand. Copying a large and
complicated object can be an expensive operation.
Implementation:
1. Overloading the member access operator in C++. The proxy behaves just like a pointer.
2. Using doesNotUnderstand in Smalltalk: to support automatic forwarding of requests.
3. Proxy doesn't always have to know the type of real subject.
Sample Code:
1. A virtual proxy. The Graphic class defines the interface for graphical objects:
class Graphic {
public:
virtual ~Graphic();
virtual void Draw(const Point& at) = 0;
virtual void HandleMouse(Event& event) = 0;

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 111


virtual const Point& GetExtent() = 0;
virtual void Load(istream& from) = 0;
virtual void Save(ostream& to) = 0;
protected:
Graphic();
};
Known Uses:
 The virtual proxy example in the Motivation section is from the ET++ text building block
classes.
 NEXTSTEP uses proxies (instances of class NXProxy) as local representatives for
objects that may be distributed.
Related Patterns:
 Adapter: An adapter provides a different interface to the object it adapts, whereas a proxy
provides the same interface as its subject.
 Decorator: A decorator adds one or more responsibilities to an object, whereas a proxy
controls access to an object.

P. Suresh, Asst. Prof., Dept. of CSE, CREC Page 112

You might also like