You are on page 1of 27

DESIGN PATTERNS-2

SYLLABUS: --------- 6 hr
Management Patterns
o Command processor
o View handler
Idioms
o Introduction
o What can idioms provide
o Idioms and style
o Where to find idioms
o Counted pointer example

Give an example design pattern for management of software system and explain briefly. ----------
--10M

Design Patterns Management


Systems must often handle collections of objects of similar kinds, of service, or even
complex components.
E.g.1 Incoming events from users or other systems, which must be interpreted and
scheduled approximately.
e.g.2 When interactive systems must present application-specific data in a variety of
different way, such views must be handled approximately, both individually and
collectively.
In well-structured s/w systems, separate manager components are used to handle
such homogeneous collections of objects.

Explain management patterns ------------------10M

For this two design patterns are described


o The Command processor pattern
o The View Handler pattern

Explain the command processor design pattern.------------------8/10M

Command Processor
The command processor design pattern separates the request for a service from its
execution.

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 1


DESIGN PATTERNS-2

A command processor component:


o Manages requests as separate objects,
o Schedules their execution, and
o Provides additional services such as the storing of request objects for later undo.

Example:

To develop a text editor (TEDDI) that provides a way to deal with mistakes made
by the user.
o Undoing the most recent change.
o Undoing of multiple changes.
The design of TEDDI includes:
o multi-level undo mechanism
o Scope for future enhancements, such as the addition of new features or a
batch mode of operation.
o Offering several means of interaction, such as keyboard input or pop-up
menus.

Context:
o Applications that need flexible and extensible user interfaces or
o Applications that provide services related to the execution of user functions, such
as scheduling or undo.

Problem:
Application needs a large set of features.
Need a solution that is well-structured for mapping its interface to its internal
functionality
Need to implement pop-up menus, keyboard shortcuts, or external control of
application via a scripting language
We need to balance the following forces:
Different users like to work with an application in different ways.
Enhancement of the application should not break existing code.

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 2


DESIGN PATTERNS-2

Additional services such as undo should be implemented consistently for all


requests.

Solution:
Use the command processor pattern which Encapsulate requests into objects
Whenever user calls a specific function of the application, the request is turned into
a command object.
The central component of our pattern description, the command processor
component which manages of all command objects.
Command processor component schedules the execution of commands
store them for later undo
Logging the sequences of commands for testing purposes.

Describe the structure solution of command-processor design pattern-----------10M

Structure:
Command processor pattern consists of following components:
1. The abstract command component
2. A command component
3. The controller component
4. The command processor component
5. The supplier component

Abstract command Component:


Defines a uniform interface of all commands objects
Procedures to execute a command
Other procedures to help command processor to perform additional services as
undo, logging,

A Command component:

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 3


DESIGN PATTERNS-2

Implements interface of abstract command by using zero or more supplier


components.
Encapsulates a function request
Uses suppliers to perform requests
E.g. bold text in text editor : save text + text position in supplier

The Controller Component:


Accepts service requests (e.g. bold text, paste text)
creates the corresponding command objects for each request
The command objects are then delivered to the command processor for activation.

Command processor Component:


Manages command objects
schedule them and activate their execution

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 4


DESIGN PATTERNS-2

implements additional services (e.g. stores commands for later undo)

The Supplier Component:


Provides functionality required to execute commands
Related commands often share suppliers
E.g. undo : supplier has to provide a means to save and restore its internal state

The following diagram shows the principal relationships between the components of the
pattern. It demonstrates undo as an example of an additional service provided by the
command processor.

Along with a neat diagram and necessary steps, describe a typical scenario of the command
processor pattern implementing an undo mechanism.-------------------10M
Divya, Asst. Professor, ISE dept., VCET, Puttur Page 5
DESIGN PATTERNS-2

Dynamics
The following diagram shows a typical scenario of the Command Processor pattern
implementing an undo mechanism. A request to capitalize a selected word arrives, is
performed and then undone.
The following steps occur:
The controller accepts the request from the user within its event loop and creates a
'capitalize' command object.
The controller transfers the new command object to the command processor for
execution and further handling.
The command processor activates the execution of the command and stores it for
later undo.
The capitalize command retrieves the currently-selected text from its supplier,
stores the text and its position in the document, and asks the supplier to actually
capitalize the selection.
After accepting an undo request, the controller transfers this request to the
command processor.
The command processor invokes the undo procedure of the most recent command.
The capitalize command resets the supplier to the previous state, by replacing the
saved text in its original position.
If no further activity is required or possible of the command, the command
processor deletes the command object.

Implementation
To implement this pattern, carry out the following steps:
1. Define the interface of the abstract command.
The abstract command class is used.
This class always specifies the abstract method required to execute a
command.

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 6


DESIGN PATTERNS-2

It also defines other methods necessary to implement the additional services


offered by the command processor.
For the undo mechanism we distinguish three types of commands.
They are modeled as an enumeration
enum CmdType { no_change, normal, no_undo };
No change: A command that requires no undo. Cursor movement
falls into this category.
Normal: A command that can be undone. Substitution of a word in
text is an example of a normal command.
No undo: A command that cannot be undone
2. Design the command components
Every command object make use supplier component for its execution.
There are several options for binding a command to its suppliers.
o The supplier component can be hardcoded within the command,
o Controller can provide the supplier to the command constructor as a
parameter.
3. Increase flexibility by providing macro commands
Macro commands combine several successive commands.
Macro commands allow user defined shortcuts to frequently-used command
sequences.
4. Implement the controller component.
Controller creates Command objects using creational patterns - Abstract
Factory and Prototype.
Prototype pattern using a generic menu controller example
Here controller creates a command prototype object for each menu
entry
Passes a copy of this object to the command processor whenever the
user selects the menu entry.

5. Implement access to the additional services of the command processor.


A user-accessible additional service is normally implemented by a specific
class.
Additional service include storing the command for later undo and
Logging the sequences of commands for testing purposes. are performed
automatically by the command processor.
6. Implement the command processor component.

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 7


DESIGN PATTERNS-2

Controller component transfers command object to the command processor


component and component processor takes responsibility for them.
For each command object, the command processor activates the execution
by calling the do method.
A command processor implemented in C++, Manages command objects
and schedules them and activates their execution.
Command processor implements additional services (e.g. stores commands
for later undo)

Variants
1. Spread controller functionality.
Role of the controller can be distributed over several components.
For example, each user interface element such as a menu button could
create a command object when activated.
2. Combination with Interpreter pattern.
Parser component takes the role of the controller.
Parser component create command objects and build the abstract syntax
tree from command objects.
Client component takes the role of the command processor.
Client does activating the commands.

Known Uses
ET++ uses command processors design pattern
o Supports unlimited, bounded, and single undo and redo.
MacApp uses the Command Processor design pattern to provide undoable
operations.
InterViews include an action class that is an abstract base class providing the
functionality of a command component.
ATM-P implements a simplified version of the Command Processor pattern
o The receiver of a command object decides how and when to execute it.

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 8


DESIGN PATTERNS-2

SICAT implements the Command Processor pattern to provide a well-defined


undo facility in the control program and the graphical SDL editors.

Write a note on:--------------------10M

a. Benefits of command processor design pattern


b. Liabilities of command processor design pattern

Consequences
The Command-Processor pattern provides the following benefits:
1. Flexibility in the way requests are activated.
a. Different user interface elements for requesting a function (input using
mouse/ keyboard) can generate the same kind of command object.
2. Flexibility in the number and functionality of requests.
a. Controller can handle any number of requests.
b. The controller and command processor are implemented independently for
individual commands.
c. Changing the implementation of a command or introducing new command
classes does not affect the command processor or other unrelated parts of
the application.
3. Programming execution-related services.
a. The central command processor provides additional services related to
command execution.
b. Additional services include log or store commands to a file for later
examination or replay.
c. A command processor can manage commands and schedule them at a later
time.
4. Testability at application level.
a. The command processor is an ideal entry point for application testing.
b. If combined with the Interpreter pattern regression tests can applied after
changes to the functional core.

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 9


DESIGN PATTERNS-2

c. Logging of command objects executed by the command processor allows


you to analyze error situations.
5. Concurrency.
a. The Command Processor design pattern allows commands to be executed
in separate threads of control.
b. Responsiveness improves, because the controller does not wait for the
execution of a command to finish.
The Command Processor pattern imposes some liabilities:
1. Efficiency loss.
a. Separate components to perform different task introduce storage and time
costs.
b. Extending such a direct controller with new requests, changing the
implementation of a service, or implementing an undo mechanism all
require more effort.
2. Potential for an excessive number of command classes.
a. Excessive number of command classes increases complexity.
b. Ways to reduce complexity:
i. Commands can be grouped around abstraction.
ii. passing the supplier object as a parameter to command classes
iii. macro-command objects
3. Complexity
a. Complexity in acquiring command parameters.
Some command objects retrieve additional parameters from the user
prior to or during their execution- this situation complicates the
event-handling mechanism.

Explain view handler design pattern------------8M

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 10


DESIGN PATTERNS-2

Design Pattern: View Handler


The View Handler design pattern helps to manage all views that a software system
provides. A view handler component allows clients to open, manipulate and dispose of
views. It also coordinates dependencies between views and organizes their update.

Example
Multi-document editors allow several documents to be worked on simultaneously.
Each document is displayed in its own window
Users can clone window and work with serveral independent views of the same
document
Changes in one window may affect other windows as well
Need an efficient update mechanism for propagating changes between windows

Context

A software system that provides multiple views of application-specific data, or that supports
working with multiple documents

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 11


DESIGN PATTERNS-2

Problem
o Need to support multiple views often need additional functionality for managing them
o Views need to be coordinated, so that update to one of them is propagated automatically
to all related views.

Forces

Managing multiple views must be easy for users and/or client components
Individual views implementation should not be depended on others
View implementation can be added during the lifetime of the system

Solution
o Separate the management of views from the code required to present or control specific
views.
o A view handler component manages all views that the software system provides
o It offers services opening, coordinating and closing views
For example, tile all views to arrange them in an orderly pattern
o Specific views component manages the functionality for their presentation and control-
one for each kind of view
o Suppliers provide views with the data they needed

Structure
View handler
o View handler is the central role, it opens new views.
o Client specify the view they want
o If the requested view is open already, the view handler brings this open view to the
foreground.
o If the requested view is open but iconized, the view handler tells the view to display itself
full size.
o It handles closing & Coordination of views
o Main service is to offer view management services

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 12


DESIGN PATTERNS-2

o For example, bring a specific view into the foreground, to refresh all views, to clone
views
o Handle dependencies between views: view that show global information should be
updated first.

Abstract view

o Abstract view component defines an interface that is common to all views


o View handler uses this interface for creating, coordinating and closing views
o Abstract view is used to execute user events, e.g. resizing the window

Specific view

o Specific view components are derived from the abstract view.


o Specific view components implement abstract interface
o Each Specific view Implements its own display function for preparing & presenting data
to the user.
o The display function is called when opening or updating a view

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 13


DESIGN PATTERNS-2

o Each Specific view gets Data are from suppliers

Supplier:

o Supplier components provide the data that is displayed by the specific view components
o Offers an interface that allows specific view to retrieve and change data.
o They notify dependent components(specific views) about change to their internal state

The OMT diagram that shows the structure of view handler pattern Component
structure and inter-relationships

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 14


DESIGN PATTERNS-2

Dynamics
Why view handler design pattern is used? Explain the scenario of the view handler creating a
new view.-------------------8M

Scenario I: shows how the view handler creates a new view

1. A client (user or another component) calls the view handler to open a particular view
2. The view handler instantiates and initializes the desired view
3. The view registers with the change-propagation mechanism of its supplier (as in
Publisher-Subscriber pattern)
4. The view handler adds the new view to its internal list of open views
5. The view handler calls the view to display itself
6. The view open a new window, retrieves data from its supplier, prepares this data for
display, and presents it to the user.

Scenario II: Organizes the tiling of views.

1. Client invokes the command to tile all open windows


2. The request is sent to the view handler
3. For all the opened view, the view handler calculates a new size and position, and calls its
resize and move procedures

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 15


DESIGN PATTERNS-2

4. Each view changes its position and size, sets the corresponding clipping area, and
refreshes the image it displays to the user
5. View will re-get the data from suppliers if necessary

Implementation

1. Identify the views

o Specify the types of views to be provided (specific or abstract view)


o How the user controls each individual view.
2. Specify a common interface for all views
o Abstract view component defines a common interface that is common to all views
o Abstract view includes functions to open, close, display, update, and manipulate a
view.
o Offers functions to initialize a view.
o Encapsulate the interface in an abstract class.

3. Implement the views


a. Implement specific view.
b. Each Specific view Implements its own display function for preparing &
presenting data to the user.
c. Each Specific view gets Data are from suppliers
4. Define the view handler

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 16


DESIGN PATTERNS-2

o Client specify the view they want, view handler is responsible for opening new
views.
o Implement methods for creating views as factory methods.
o View handler maintains references to all open views internally. Iterator pattern is
used to implement this functionality.
o View handler maintains additional information such as current position & size of
window on the screen.
o It handles closing & Coordination of views (uses coordination policies)
o Main service is to offer view management services
o If the requested view is open already, the view handler brings this open view to
the foreground.
o If the requested view is open but iconized, the view handler tells the view to
display itself full size.
o Handle dependencies between views: view that show global information should
be updated first.
o Supports refreshing all views, to clone views, to tile views, close views

Variants
View Handler with Command objects
- use command objects to keep the view handler independent of specific view interfaces
- View handler creates command objects & these command objects operates on specific
view.

Known Uses
1. Macintosh Window Manager
- Macintosh toolbox
o The Window Manager is the part of Macintosh toolbox
o Window Manager is equal to view handler component.
o Interface offers functions for window allocation, window display, mouse
location, window movement and sizing etc.
- It only provides support for handling individual windows

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 17


DESIGN PATTERNS-2

- Does not offer functions that operate on several windows.


2. Microsoft Word
The Microsoft Word word-processing system offers functions
a. Cloning, tiling windows.
b. Bringing an open window into the foreground.
c. Dialog boxes are displayed requesting the desired action if a window
contains data that has been changed but not saved.

Write a note on:--------------------10M

c. Benefits of view handler design pattern


d. Liabilities of view handler design pattern

Consequences
Advantages
1) Uniform handling of views
a. All views share a common interface (abstract view)
b. View handler: handle and manipulate all views uniformly, Independent of what
they display and how they are implemented.
2) Extensibility and changeability of views
a. Support integration of new views without changes to existing views & view
handler.
b. change in the implementation of one view do not affect other components
3) Application-specific view coordination
a. Views are managed by a central instance.
b. Easy--- to implement specific view coordination strategies (View handler)

Disadvantages
1) Restricted applicability
a. View Handler pattern is useful if the system must support many different views
b. Useful when views have logical dependencies between each other and make use
of view coordination strategies.
c. Useful when views view make use of different suppliers.

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 18


DESIGN PATTERNS-2

If none of these apply then using view handler pattern deals to: additional implementation
effort & increases the complexity of the system
2) Efficiency
a. Efficiency loss due to propagation of change notifications to all specific
views.
b. If view handler is responsible to organizing view updating then this results
in a loss of performance.
See Also
The Model-View-Controller architectural pattern :
From the perspective of MVC the View Handler pattern is a refinement of the
relationship between the model and its associated views.
The Presentation-Abstraction-Control architectural pattern:
An intermediate level PAC agent that creates and coordinates views corresponds to
the view handler. Bottom-level view PAC agents that present data to the user
represent the view components.

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 19


DESIGN PATTERNS-2

What are idioms? How do they differ from design patterns? Explain the necessary steps for
implementing the counted pointer idioms. -------------------10M

Idioms
Introduction
Def: An idiom is a low-level pattern specific to a programming language. An idiom
describes how to implement particular aspects of components or the relationships
between them using the features of the given language.

Design patterns Idioms

Medium-scale patterns. Low-level patterns.

A design pattern provides a scheme for refining An idiom is a low-level pattern


the subsystems or components of a software specific to a programming language.
system, or the relationships between them. An idiom describes how to
It describes a commonly-recurring structure of implement particular aspects of
communicating components that solves a general components or the relationships
design problem within a particular Context.
between them using the features of
the given language.

Problems related to language. Less


Independent of particular programming language. portable between the programming
Portable between the programming languages. languages.

What Can Idioms Provide?


A single idiom might help you to solve a recurring problem with the programming
language you normally use.
Example of such a problem are Memory management, object creation,
naming of methods, source code formatting for readability, efficient use of
library component
They provide a vehicle for communication among software developers. Because
each idiom has a unique name
Idioms are less 'portable between programming languages.
Idioms for object creation in C++ are not portable to solve the problem of object
creation in java.

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 20


DESIGN PATTERNS-2

What are idioms and styles? Explain with the help of an example, a style guide idiom.------------
6/5M

Idioms and Style


Even for experienced programmer it is difficult to follow consistent style.
If programmers who use different styles form a team, they should agree on a single
coding style for their programs.
String copy function for 'C-style' string:
void strcopyKR(char *d, const char *s)
{
while(*d++ = *s++);
}
-------------------------------------------------------------------------------
void strcopyPascal(char d[ ], const char s[ ])
{
int i;
for (i=0; s[i] != \0 ; i=i+1)
{
d[i] = s[i];
} d[i] = \0;
}
Both functions achieve same results:
strcopyKR: copy characters from string s to string d until a character with the value
zero is reached.
Function uses pointers concept for string copy.

strcopyPascal: .depicts the copying mechanism from one array to another.

A program that uses a mixture of both styles might be much harder to understand
and maintain.
Corporate style guides are one approach to achieving a consistent style throughout
programs developed by teams.
Divya, Asst. Professor, ISE dept., VCET, Puttur Page 21
DESIGN PATTERNS-2

Style guides that contain idioms.


These use dictatorial rules like all comments must start on a separate line.
They not only give the rules, but also provide solution to problems.

Here is an example of a style guide idiom from Kent Beck's Smalltalk Best Practice
Patterns :
Name : Indented Control Flow
Problem : How do you indent messages?
Solution : Put zero or one argument messages on the same lines as their receiver.
foo isNil
2+3
a < b ifTrue: [ . . . ]
Put the keyword/argument pairs of messages with two or more keywords each on its own
line, indented one tab.
a<b
ifTrue: [ . . . ]
ifFalse: [ . . . ]

Where Can You Find Idioms?


Explain singleton design pattern that provides 2 idioms specific to small talk and C++------------
---6M

Some design patterns also provides a source of idioms.


Singleton design pattern that provides 2 idioms specific to small talk and C++

Name: Singleton (C++)


Problem: To ensure that exactly one instance of a class exists at runtime.
Solution:
- Make the constructor of the class private.
- Declare a static member variable the Instance that refers to the single existing
instance of the class. Initialize this pointer to zero.

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 22


DESIGN PATTERNS-2

- Define a public static member function getInstance( ) that returns the value of
theInstance.
- The first time getInstance( ) is called, which creates the single instance with new
and assign its address to theInstance.
Example
class Singleton {
static Singleton* theInstance;
Singleton();
public:
static Singleton* getInstance() {
if ( theInstance == 0 )
theInstance = new Singleton();
return theInstance;
}
};
//
Singleton* Singleton::theInstance = 0;

----**-----
Name: Singleton (smalltalk)
Problem: To ensure that exactly one instance of a class exists at runtime.
Solution:
- Override the class method new to raise an error.
- Add a class variable TheInstance that holds the single instance.
- Implement a class method getInstance that returns TheInstance. The first time
getInstance is called.
- It will create the single instance with super new and assign it to theInstance.

new self-error: cannot create new object


getInstance
TheInstance isNil ifTrue: [TheInstance := super new].
^ theInstance

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 23


DESIGN PATTERNS-2

Counted pointer
The Counted Pointer idiom
makes memory management of dynamically-allocated shared objects in C++ easier. It
introduces a reference counter to a body class that is updated by handle objects. Clients
access body class objects only through handles via the overloaded operator-> ( ) .

Example
When using C++ for object-oriented development, memory management is an
important issue.
Whenever an object is shared by clients each of which holds a reference to it.
Two situations exist that are likely to cause problems:
a client may delete the object while another client still holds a reference to it
All clients may 'forget' their references without the object being deleted.

Context
Memory management of dynamically allocated instances of a class.
Problem
If you have to deal with references or pointers to dynamically allocated objects of a class,
you may need to address the following forces:
1. Passing objects by value is inappropriate for a class.

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 24


DESIGN PATTERNS-2

If the object is passed by value then complier will automatically destroy the
object when it goes out of scope.
But solution(Passing objects by value) does not work well for 3 reasons:
1. If the object is large, copying each time is expensive in run-time and
memory consumption.
2. Object with dynamic data structure such as directed graph, trees is
impossible to create in C++
3. Not possible to share objects.
2. Several clients may need to share the same object.
You want to avoid 'dangling' references-references to an object that has
been deleted.
If a shared object is no longer needed, it should be destroyed to conserve
memory and release other resources it has acquired.
3. Your solution should not require too much additional code within each client.

Solution
The Counted Pointer idiom eases memory management of shared objects.
Body class is class of shared objects. A reference counter is used to keep track of
references used.
Handle class: handle object holds references to body objects. All Handle Objects are
passed by value and therefore they are allocated and destroyed automatically. Handle class
takes care body objects reference counter. By overloading operator() in the handle
class, body objects can be used syntactically.

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 25


DESIGN PATTERNS-2

Write down the steps to implement the counter pointer idiom.----------------6/6/8M

Implementation
To implement the Counted Pointer idiom, carry out the following steps:
1. Make the constructors and destructor of the Body class private (or protected) to
prohibit its uncontrolled instantiation and deletion.
2. Make the Handle class a friend to the Body class, and thus provide the Handle class
with access to Body's private variables and methods.
3. Extend the Body class with a reference counter.
4. Add a single data member to the handle class that points to the body object.
5. In the Handle class, implement a copy constructor and an assignment operator
that copy the pointer to the body object
increment the body objects reference count.
Implement the destructor of the Handle class
decrement the reference counter
delete the Body object when the counter reaches zero.
6. Implement the arrow operator of the Handle class as follows:
Body * operator->() { return body; }
and make it a public member function.
5. Extend the Handle class with one or several constructors that create the initial body
instance for the first time.
These constructors should set the reference counter to one.

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 26


DESIGN PATTERNS-2

Divya, Asst. Professor, ISE dept., VCET, Puttur Page 27

You might also like