Software Patterns
Software Patterns
: 1
IBM-Rational Software Architect v6Installation Guide
Date:
AIM:
Double click on the downloaded executable. This will start the installation process.
This is start the installation process. This may take a few minutes.
Ensure that Start the Installation Wizard is checked. Press Finish when creating the installation
image completes. This will start the installation wizard.
This will start the installation. This may take a few minutes.
Choose Next to continue when the installation returns.
Result:
Experiment No.: 2
Using UML design one of the Creational Patterns (Abstract factory).
Date:
AIM:
Benefits:
Usage:
When the system needs to be independent of how its products are created composed and
represented.
When the system needs to be configured with one of multiple families of products.
When a family of products need to be used together and this constraint needs to be
enforced.
When you need to provide a library of products, expose their interfaces not the
implementation.
Result:
Experiment No.: 3
Using UML design one of the Creational Patterns (Builder Pattern).
Date:
AIM:
It separates the construction of a complex object from its representation so that the same
construction process can create different representations.
Class Diagram
Builder:
Specifies an abstract interface for creating parts of a Product object
ConcreteBuilder.
Constructs and assembles parts of the product by implementing the Builder interface
Defines and keeps track of the representation it creates
Provides an interface for retrieving the product
Director.
Constructs an object using the Builder interface
Product.
Represents the complex object under construction. Concrete Builder builds the product's
internal representation and defines the process by which it's assembled
Includes classes that define the constituent parts, including interfaces for assembling the parts
into the final result
Example: PromoKitBuilder
PromoKitBuilder (Builder)
PromoKitBuilder specifies an abstract interface for creating parts of a PromoKit (Product)
object
MenPromoKitBuilder, WomenPromoKitBuilder (ConcreteBuilder).
MenPromoKitBuilder, WomenPromoKitBuilder constructs and assembles parts of the product
by implementing the PromoKitBuilder (Builder) interface
It defines and keeps track of the representation it creates
It provides an interface for retrieving the product
PromoKitDirector (Director)
PromoKitDirector constructs an object using the PromoKitBuilder (Builder) interface
PromoKit (Product)
PromoKit represents the complex object under construction. MenPromoKitBuilder,
WomenPromoKitBuilder (ConcreteBuilder) builds the product's internal representation and
defines the process by which it's assembled
PromoKit includes classes that define the constituent parts, including interfaces for assembling
the parts into the final result, they are Garment, Video, Book classes
Usage:
The algorithm for creating a complex object should be independent of both the parts that make
up the object and how the parts are assembled.
The construction process must allow different representations of the constructed object
Result:
Experiment No.: 4
Using UML design one of the Structural Patterns (Façade Pattern).
Date:
AIM:
Class Diagram:
Facade.
It knows which subsystem classes are responsible for a request.
It delegates client requests to appropriate subsystem objects.
Subsystem classes.
It implements subsystem functionality.
It handles work assigned by the Facade object
It has no knowledge of the facade and keeps no reference to it.
Example: Process
Process (Façade)
Process knows which subsystem (FTPProcessing, ZIPProcessing, or ProcessFiles) classes
are responsible for a request.
Process delegates client requests to appropriate subsystem (FTPProcessing,
ZIPProcessing, or ProcessFiles) objects.
Subsystem classes.
FTPProcessing, ZIPProcessing, or ProcessFiles implements subsystem functionality.
FTPProcessing, ZIPProcessing, or ProcessFiles handles work assigned by the Facade object
FTPProcessing, ZIPProcessing, or ProcessFiles have no knowledge of the facade and keep
no reference to it.
Example: Class Diagram
Benefits:
Provides a simple interface to a complex system without reducing the functionality
provided by the system.
Shields clients from complexity of subsystem components.
Promotes weak coupling between the subsystem and its clients.
Reduces coupling between subsystems if every subsystem uses its own facade pattern.
Translates client requests to the subsystems that can fulfil those requests.
Usage:
When you want to provide a simple interface to a complex subsystem.
When there are many dependencies between clients and the implementation classes of an
abstraction.
When you want to layer your subsystems.
Result:
Experiment No.: 5
Using UML design one of the Structural Patterns (Bridge Pattern).
Date:
AIM:
Decouple an abstraction from its implementation so that the two can vary independently.
Class Diagram:
Abstraction.
Defines the abstraction's interface.
Maintains a reference to an object of type Implementor.
RefinedAbstraction.
Extends the interface defined by Abstraction.
Implementor.
Defines the interface for implementation classes. This interface doesn't have to correspond
exactly to Abstraction's interface; in fact the two interfaces can be quite different. Typically the
Implementation interface provides only primitive operations, and Abstraction defines higher-
level operations based on these primitives.
ConcreteImplementor.
Implements the Implementor interface and defines its concrete implementation.
Example: Material
Dishware (Abstraction).
Dishware defines the abstraction's interface.
Dishware maintains a reference to an object of type Material (Implementor).
Plate, Bowl (RefinedAbstraction).
Plate, Bowl extends the interface defined by Dishware (Abstraction).
Material (Implementor).
Material defines the interface for implementation classes. This interface doesn't have to
correspond exactly to Dishware (Abstraction's) interface; in fact the two interfaces can be quite
different. Typically the Material (Implementation) interface provides only primitive operations,
and Dishware (Abstraction) defines higher-level operations based on these primitives.
Wood, Glass (ConcreteImplementor).
Wood, Glass implements the Material (Implementor) interface and defines its concrete
implementation.
Usage:
When you want to avoid a permanent binding between an abstraction and its implementation
When both the abstraction and implementations should be extensible using subclasses.
When changes in the implementation of an abstraction should have no impact on clients,
which means that you should not have to recompile their code.
Result:
Experiment No.: 6
Using UML design one of the Structural Patterns (Decorator Pattern).
Date:
Aim:
Class Diagram:
Component.
Defines the interface for objects that can have responsibilities added to them dynamically.
ConcreteComponent.
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.
Concrete Decorator.
Adds responsibilities to the component.
Example: Book Service
BookService (Component).
BookService defines the interface for objects that can have responsibilities added to them
dynamically.
BookServiceImpl (ConcreteComponent).
BookServiceImpl defines an object to which additional responsibilities can be attached.
BookServiceDecorator (Decorator).
BookServiceDecorator maintains a reference to a BookService (Component) object and defines
an interface that conforms to BookService’s (Component's) interface.
BookServiceDecoratorImpl (ConcreteDecorator).
BookServiceDecoratorImpl adds responsibilities to the BookService (component).
Benefits:
More flexibility than static inheritance.
Avoids feature-leads classes high up in the hierarchy.
Simplifies coding because you write a series of classes each targeted at a specific part of the
functionality rather than coding all behaviour into the object.
Enhances the object's extensibility because you make changes by coding new classes.
Usage:
When you want to add responsibilities to individual objects dynamically and transparently,
without affecting other objects.
When you want to add responsibilities to the object that you might want to change in the
future.
When extension by static sub classing is impractical.
Result:
Experiment No.: 7 User gives a print command from a word document. Design to
Date: represent this Singleton design Pattern.
AIM:
Singleton Pattern
a.Motivation
The singleton pattern is one of the simplest design patterns: it involves only one class which is
responsible to instantiate itself, to make sure it creates not more than one instance; in the same
time it provides a global point of access to that instance. In this case the same instance can be
used from everywhere, being impossible to invoke directly the constructor each time.
b.Intent
Ensure that only one instance of a class is created.
Provide a global point of access to the object.
c. Implementation
The implementation involves a static member in the "Singleton" class, a private constructor and
a static public method that returns a reference to the static member.
The Singleton Pattern defines a getInstance operation which exposes the unique instance which
is accessed by the clients. getInstance() is responsible for creating its class unique instance in
case it is not created yet and to return that
instance.
e. Applicability & Examples
According to the definition the singleton pattern should be used when there must be exactly one
instance of a class, and when it must be accessible to clients from a global access point. Here are
some real situations where the singleton is used:
f. Example 1 - Logger Classes
The Singleton pattern is used in the design of logger classes. This classes are ussualy
implemented as a singletons, and provides a global logging access point in all the application
components without being necessary to create an object each time a logging operations is
performed.
i. Serialization
If the Singleton class implements the java.io.Serializable interface, when a singleton is serialized
and then deserialized more than once, there will be multiple instances of Singleton created.
Multithreading - A special care should be taken when singleton has to be used in a
multithreading application.
Serialization - When Singletons are implementing Serializable interface they have to implement
read Resolve method in order to avoid having 2 different objects.
Classloaders - If the Singleton class is loaded by 2 different class loaders we'll have 2 different
classes, one for each class loader.
Global Access Point represented by the class name - The singleton instance is obtained using the
class name. At the first view this is an easy way to access it, but it is not very flexible. If we need
to replace the Singleton class, all the references in the code should be changed accordingly.
Hot Spot:
Multithreading - A special care should be taken when singleton has to be used in a
multithreading application.
Serialization - When Singletons are implementing Serializable interface they have to implement
read Resolve method in order to avoid having 2 different objects.
Classloaders - If the Singleton class is loaded by 2 different class loaders we'll have 2 different
classes, one for each class loader.
Global Access Point represented by the class name - The singleton instance is obtained using the
class name. At the first view this is an easy way to access it, but it is not very flexible. If we need
to replace the Singleton class, all the references in the code should be changed accordingly.
Result:
Experiment No.: 8 Using UML design one of the Behavioural Patterns (Chain of
Date: responsibility).
AIM:
Intent:
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.
Launch-and-leave requests with a single processing pipeline that contains many possible
handlers.
An object-oriented linked list with recursive traversal.
Problem:
There is a potentially variable number of "handler" or "processing element" or "node" objects, and a
stream of requests that must be handled. Need to efficiently process the requests without hard-
wiring handler relationships and precedence, or request-to-handler mappings.
Discussion:
Encapsulate the processing elements inside a "pipeline" abstraction; and have clients "launch
and leave" their requests at the entrance to the pipeline.
The pattern chains the receiving objects together, and then passes any request messages from
object to object until it reaches an object capable of handling the message. The number and type of
handler objects isn't known a priori, they can be configured dynamically. The chaining mechanism
uses recursive composition to allow an unlimited number of handlers to be linked.
Chain of Responsibility simplifies object interconnections. Instead of senders and receivers
maintaining references to all candidate receivers, each sender keeps a single reference to the head of
the chain, and each receiver keeps a single reference to its immediate successor in the chain.
Make sure there exists a "safety net" to "catch" any requests which go unhandled.
Do not use Chain of Responsibility when each request is only handled by one handler, or, when the
client object knows which service object should handle the request.
Structure:
The derived classes know how to satisfy Client requests. If the "current" object is not available or
sufficient, then it delegates to the base class, which delegates to the "next" object, and the circle of life
continues.
Multiple handlers could contribute to the handling of each request. The request can be
passed down the entire length of the chain, with the last link being careful not to delegate to a "null
next".
Example
The Chain of Responsibility pattern avoids coupling the sender of a request to the receiver by giving
more than one object a chance to handle the request. ATM use the Chain of Responsibility in money
giving mechanism.
Check list:
Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple
senders and receivers, but with different trade-offs. Chain of Responsibility passes a sender
request along a chain of potential receivers.
Chain of Responsibility can use Command to represent requests as objects.
Chain of Responsibility is often applied in conjunction with Composite. There, a component's
parent can act as its successor.
Code examples:
Java Chain of Responsibility in Java: Before Chain of Responsibility in Java
and after
Result:
Experiment No.: 9 Identify the application where we can use multiple creational patterns
Date: and implement it
AIM:
Many a time when you design or implement solutions for a software system, you get the
feeling of dij` vu. Even though this may sound too extreme, it is undeniable that parts of different
software systems may share similar aspects. With software design going the assembly line way,
reusability has become an important criterion in software design
A pattern is a commonly occurring reusable piece in software system that provides a certain set
of functionality. The identification of a pattern is also based on the context in which it is used. So,
using patterns in modeling of systems helps in keeping design standardized and more importantly,
minimizes the reinventing of the wheel in the system design. This article is all about patterns;
especially design patterns.
Over the previous articles in this series, we explored the different UML diagrams and learned
how to model each of the diagrams in a case study application. Building on this background we will
see how to leverage the usefulness of well-known patterns to make application designing a lot
easier.
Useful solution
Reusable
Contextual
Design Patterns
Since a system is made up of static as well as dynamic elements, you will find patterns that
can be used for either of these types. For static elements of a system especially the architecture and
design of a system, there are design patterns - the focus of this article. The dynamic aspects of a
system are abstracted and captured as process patterns. But patterns are not limited to this. Patterns
can be abstracted for the implementation aspects of a system as well.
Based on how they are to be used, patterns are primarily categorized as:
Creational
Structural
Behavioural
Creational Patterns:
The first type of design pattern is the creational pattern. Creational patterns provide ways to
instantiate single objects or groups of related objects. There are five such patterns:
Abstract Factory. The abstract factory pattern is used to provide a client with a set of related or
dependant objects. The "family" of objects created by the factory are determined at run-time.
Builder. The builder pattern is used to create complex objects with constituent parts that must
be created in the same order or using a specific algorithm. An external class controls the
construction algorithm.
Factory Method. The factory pattern is used to replace class constructors, abstracting the
process of object generation so that the type of the object instantiated can be determined at run-
time.
Prototype. The prototype pattern is used to instantiate a new object by copying all of the
properties of an existing object, creating an independent clone. This practise is particularly
useful when the construction of a new object is inefficient.
Singleton. The singleton pattern ensures that only one object of a particular class is ever
created. All further references to objects of the singleton class refer to the same underlying
instance.
Creational:
Creational patterns define mechanisms for instantiating objects. The implementation of the
creational pattern is responsible for managing the lifecycle of the instantiated object. A few examples
of Creational design patterns are listed below.
Factory:
One of the easily recognized and frequently used design patterns is the Factory pattern. If
you have designed any object that is responsible for creating and maintaining the lifecycle of another
object, you have used the Factory pattern. Obtaining a database connection in your application using
a connection manager or connection factory object is a good example of the Factory pattern.
Result:
Experiment No.: 10 Identify the application where we can use multiple structural patterns
Date: and implement it
AIM:
Structural Patterns:
The second type of design pattern is the structural pattern. Structural patterns provide a manner
to define relationships between classes or objects.
Adapter. The adapter pattern is used to provide a link between two otherwise incompatible
types by wrapping the "adaptee" with a class that supports the interface required by the client.
Bridge. The bridge pattern is used to separate the abstract elements of a class from the
implementation details, providing the means to replace the implementation details without
modifying the abstraction.
Composite. The composite pattern is used to create hierarchical, recursive tree structures of
related objects where any element of the structure may be accessed and utilised in a standard
manner.
Decorator. The decorator pattern is used to extend or alter the functionality of objects at run-
time by wrapping them in an object of a decorator class. This provides a flexible alternative to
using inheritance to modify behaviour.
Facade. The facade pattern is used to define a simplified interface to a more complex subsystem.
Flyweight. The flyweight pattern is used to reduce the memory and resource usage for complex
models containing many hundreds, thousands or hundreds of thousands of similar objects.
Proxy. The proxy pattern is used to provide a surrogate or placeholder object, which references
an underlying object. The proxy provides the same public interface as the underlying subject
class, adding a level of indirection by accepting requests from a client object and passing these
to the real subject object as necessary.
Structural
The composition of objects and their organization to obtain new and varied functionality is
the underlying basis of Structural patterns. A few examples of Structural design patterns are listed
below.
Adapter:
In the Adapter pattern, an object provides an implementation of an interface used by other
objects in a consistent way. The adapter object wraps different disparate implementations of the
interface and presents a unified interface for other objects to access. A good example of this is a
database driver like an ODBC (Open Database Connectivity) or JDBC (Java Database Connectivity)
driver that wraps the custom database accessing implementation for different databases and yet,
presents a consistent interface that is a published and standardized API.
Proxy:
A Proxy pattern constitutes use of proxy objects during object interaction. A proxy object acts
as a substitute for the actual object. Use of proxy objects is prevalent in remote object interaction
protocols. As an example, when an object needs to interact with a remote object, say across a
network, the most preferred way of encapsulating and hiding the interaction mechanism is by using
a proxy object that mediates communication between the requesting object and the remote object.
Result:
Experiment No.: 11 Identify the application where we can use multiple behavioural
Date: patterns and implement it
AIM:
Behavioural Patterns:
The final type of design pattern is the behavioral pattern. Behavioral patterns define manners of
communication between classes and objects.
Chain of Responsibility. The chain of responsibility pattern is used to process varied requests,
each of which may be dealt with by a different handler.
Command. The command pattern is used to express a request, including the call to be made
and all of its required parameters, in a command object. The command may then be executed
immediately or held for later use.
Interpreter. The interpreter pattern is used to define the grammar for instructions that form part
of a language or notation, whilst allowing the grammar to be easily extended.
Iterator. The iterator pattern is used to provide a standard interface for traversing a collection of
items in an aggregate object without the need to understand its underlying structure.
Mediator. The mediator pattern is used to reduce coupling between classes that communicate
with each other. Instead of classes communicating directly, and thus requiring knowledge of
their implementation, the classes send messages via a mediator object.
Memento. The memento pattern is used to capture the current state of an object and store it in
such a manner that it can be restored at a later time without breaking the rules of encapsulation.
Observer. The observer pattern is used to allow an object to publish changes to its state. Other
objects subscribe to be immediately notified of any changes.
State. The state pattern is used to alter the behaviour of an object as its internal state changes.
The pattern allows the class for an object to apparently change at run-time.
Strategy. The strategy pattern is used to create an interchangeable family of algorithms from
which the required process is chosen at run-time.
Template Method. The template method pattern is used to define the basic steps of an
algorithm and allow the implementation of the individual steps to be changed.
Visitor. The visitor pattern is used to separate a relatively complex set of structured data classes
from the functionality that may be performed upon the data that they hold.
Behavioural
Interaction between different objects is specifically covered by Behavioral patterns. Some
examples of behavioral patterns are given below.
Command:
The Command pattern is commonly used for gathering requests from client objects and
packaging them into a single object for processing. The Command pattern allows for having well
defined command interfaces that are implemented by the object that provides the processing for the
client requests packaged as commands.
Iterator:
A simple mechanism to traverse and access a list of objects is defined by the Iterator pattern.
The Iterator pattern encapsulates the internal implementation of the list while providing a
standardized mechanism for list traversal.
One of the simplest design patterns that we can identify is the Behavioral pattern. The methods in
the classes of the Courseware Management System that return multiple results, like the view
Courses () method of the Course Administrator class, will use the Iterator pattern to iterate through
the list of courses in the system.
We can identify at least a couple of examples of Structural patterns. For instance, one
component that is not shown in the class diagram is a database accessing element that will provide
database accessing services for all the classes in the class diagram that need to interact with a data
store. All database interactions to retrieve or update information required for their business
functionality can be routed through this database access element, which acts as a bridge between the
database and the application components. This is an example of the Bridge design pattern.
f we take things to the implementation level, we can define a common interface object that is used to
package data passed between the different classes. This would help to keep the interface between
interacting classes the same while allowing for flexibility in implementation. Such a common
interface object is a good example of the Value Object pattern that falls under the category of
Structural design pattern.
Result: