Professional Documents
Culture Documents
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
Command Processor
The command processor design pattern separates the request for a service from its
execution.
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.
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.
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
A Command component:
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.
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.
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.
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
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
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
Specific view
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
Dynamics
Why view handler design pattern is used? Explain the scenario of the view handler creating a
new view.-------------------8M
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.
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
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
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.
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.
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.
What are idioms and styles? Explain with the help of an example, a style guide idiom.------------
6/5M
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
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: [ . . . ]
- 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.
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.
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.
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.