100% found this document useful (1 vote)
51 views138 pages

Design Pattern ch-2

Designing reusable object-oriented software involves identifying relevant objects, creating classes, and defining interfaces while ensuring flexibility for future needs. Design patterns serve as proven solutions to common software design challenges, enhancing code structure and reusability. The document discusses various design patterns, including Factory Method, Singleton, Prototype, and Builder, outlining their principles, use cases, and components.

Uploaded by

mumubrown706
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
51 views138 pages

Design Pattern ch-2

Designing reusable object-oriented software involves identifying relevant objects, creating classes, and defining interfaces while ensuring flexibility for future needs. Design patterns serve as proven solutions to common software design challenges, enhancing code structure and reusability. The document discusses various design patterns, including Factory Method, Singleton, Prototype, and Builder, outlining their principles, use cases, and components.

Uploaded by

mumubrown706
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 138

Designing reusable


Designing reusable object-oriented software is challenging
due to the need to find relevant objects, factor them into
classes, define interfaces and inheritance hierarchies, and
establish key relationships.

The design should be specific to the problem at hand but
general enough to address future requirements.

Reuseability and flexibility are difficult to achieve the first
time, as experienced designers often try to reuse the design
multiple times, modifying it each time.
Cont

Experienced object-oriented designers excel in creating good designs, while
newcomers often rely on non-object-oriented techniques.

Expert designers reuse past solutions, creating recurring patterns of classes
and communicating objects in their systems.

This approach makes object-oriented designs more flexible, elegant, and
reusable, allowing designers to apply successful designs without rediscovering
them.

This approach is similar to how novelists and playwrights follow patterns, such
as "Tragically Flawed Hero" or "The Romantic Novel."
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.

Even though Alexander was talking about patterns in buildings and towns,
what he says is true about object-oriented design patterns.

Our solutions are expressed in terms of objects and interfaces instead of
walls and doors, but at the core of both kinds of patterns is a solution to a
problem in a context.
Software design patterns


Software design patterns are important tools developers, providing proven
solutions to common problems encountered during software development.

Reusable solutions for typical software design challenges are known as design
patterns.

Expert object-oriented software engineers use these best practices to write more
structured, manageable, and scalable code.

Design patterns provide a standard terminology and are specific to particular
scenarios and problems.

Design patterns are not finished code but templates or blueprints only.

A pattern is a design tool that consists of four essential elements: pattern name,
problem, solution, and consequences.

The pattern name helps expand our design vocabulary and allows us to discuss and
communicate designs and their trade-offs.

The problem describes when to apply the pattern, describing the problem and its context.

The solution describes the elements of the design, their relationships, responsibilities, and
collaborations.

The consequences are the results and trade-offs of applying the pattern, crucial for
evaluating design alternatives and understanding the costs and benefits.

Software design can have consequences such as space and time
trade-offs, language and implementation issues, and the impact
on flexibility, extensibility, or portability.

Design patterns are descriptions of communicating objects and
classes customized to solve a general design problem in a
particular context.

They identify key aspects of a common design structure that
make it useful for creating reusable object-oriented designs.
Smalltalk MVC


Smalltalk MVC is a user interface framework that uses the
Model/View/Controller (MVC) triad of classes to build user interfaces.

MVC consists of three types of objects: Model, View, and Controller.

MVC decouples these objects to increase flexibility and reuse.

It establishes a subscribe/notify protocol between views and models, allowing
for multiple views to be attached to a model and the creation of new views
without rewriting it.

This approach allows for more flexible and reused user interfaces.

The following diagram shows a model and three views.
(We've left out the controllers for simplicity.)

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.

The MVC (Model View) design pattern allows for the implementation of
complex views with nested button views, allowing for reuse in a debugger.

The CompositeView class, a subclass of View, supports nested views and
can be used wherever a view can be used.

This design is applicable to grouping objects and treating them as individual
objects.

It allows for a class hierarchy where subclasses define primitive objects and
composite objects (CompositeView) that assemble them into more complex
objects.
1.3 Describing Design Patterns
How do we describe design patterns? Graphical notations, while important and useful,
aren't sufficient. They simply capture the end product of the design process as
relationships between classes and objects.
To reuse the design, we must also record the decisions, alternatives, and trade-offs that led
to it. Concrete examples are important too, because they help you see the design in action.
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
A short statement that answers the following questions: 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) [RBP+91]. We also use interaction
di-agrams [JCJO92, Boo94] 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.
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 he 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?
The appendices provide background information that will help you understand the
patterns and the discussions surrounding them
.

.
How Design Patterns Solve Design Problems

Design patterns solve many of the day-to-day problems object-oriented designers
face, and in many different ways.

Here are several of these problems and how design patterns solve them.

Finding Appropriate Objects

Object-oriented programs are made up of objects. An object packages both data and

the procedures that operate on that data.

The procedures are typically called methods or operations.

An object performs an operation when it receives a request (or message) from a
client.

Object-oriented design involves encapsulating an object's internal state,
making it difficult to access and change its representation.

Decomposing a system into objects is challenging due to factors like
encapsulation, dependency, flexibility, performance, evolution, and reusability.

Various approaches are used, including problem statements, focusing on
collaborations, modeling the real world, and translating objects from analysis.

However, object-oriented designs often result in classes with no counterparts
in the real world, making them flexible and addressing current realities.
Why Learn Design Patterns?


There are multiple reasons to learn design patterns:

Code that is simpler to comprehend, update, and expand is produced with the
help of design patterns.

They offer solutions that have been tried and tested as well as best practices.

Learning this enables them to quickly and effectively address similar challenges
in various projects.

Developers can produce reusable components that can be utilized in a variety of
applications by implementing design patterns.

This reduces redundancy and saves development time.
Types of Software Design Patterns


Types of Software Design Patterns

There are three types of Design Patterns:

Creational Design Pattern

Structural Design Pattern

Behavioral Design Pattern
1. Creational Design Patterns


Creational Design Patterns focus on the process of object creation or problems related to
object creation.


They help in making a system independent of how its objects are created, composed and represented.
Factory method Design Pattern


The Factory Method Design Pattern is a
creational design pattern that provides an interface for creating
objects in a superclass, allowing subclasses to alter the type of
objects that will be created.

This pattern is particularly useful when the exact types of
objects to be created may vary or need to be determined at
runtime, enabling flexibility and extensibility in object creation.
What is the Factory Method Design Pattern?


The Factory Method Design Pattern is a creational design pattern used in software
development. It provides an interface for creating objects in a superclass while allowing
subclasses to specify the types of objects they create.


This pattern simplifies the object creation process by placing it in a
dedicated method, promoting loose coupling between the object creator and
the objects themselves.

This approach enhances flexibility, extensibility, and maintainability, enabling
subclasses to implement their own factory methods for creating specific
object types.
When to Use the Factory Method Design Pattern


Below is when to use factory method design pattern:


If your object creation process is complex or varies under different conditions, using a factory method can make your
client code simpler and promote reusability.


The Factory Method Pattern allows you to create objects through an interface or abstract class, hiding the details of
concrete implementations.


This reduces dependencies and makes it easier to modify or expand the system without affecting existing code.


If your application needs to create different versions of a product or may introduce new types in the future, the Factory
Method Pattern provides a flexible way to handle these variations by defining specific factory methods for each product
type.


Factories can also encapsulate configuration logic, allowing clients to customize the object creation process by providing
parameters or options to the factory method.
Components of Factory Method Design Pattern


Below are the main components of Factory Design Pattern:


Creator: This is an abstract class or an interface that declares the factory method. The creator typically
contains a method that serves as a factory for creating objects. It may also contain other methods that work
with the created objects.


Concrete Creator: Concrete Creator classes are subclasses of the Creator that implement the factory method
to create specific types of objects. Each Concrete Creator is responsible for creating a particular product.


Product: This is the interface or abstract class for the objects that the factory method creates. The Product
defines the common interface for all objects that the factory method can create.


Concrete Product: Concrete Product classes are the actual objects that the factory method creates. Each
Concrete Product class implements the Product interface or extends the Product abstract class.
Singleton Method Design Pattern

The Singleton Method Design Pattern ensures a class has only one instance and provides a global access point to
it.


It’s ideal for scenarios requiring centralized control, like managing database connections or configuration settings.


Singleton Design Pattern Principles


Single Instance: Singleton ensures that only one instance of the class exists throughout the application.


Global Access: Provide a global point of access to that instance.


Lazy or Eager Initialization: Support creating the instance either when needed (lazy) or when the class is loaded (eager).


Thread Safety: Implement mechanisms to prevent multiple threads from creating separate instances simultaneously.


Private Constructor: Restrict direct instantiation by making the constructor private, forcing the use of the access point
When to use Singleton Method Design Pattern?


Use the Singleton method Design Pattern when:

Consider using the Singleton pattern when you need to ensure that only one instance of a class exists in your
application.


Use it when you want to provide a straightforward way for clients to access that instance from a specific location in
your code.


If you think you might want to extend the class later, the Singleton pattern is a good choice.


It allows for subclassing, so clients can work with the extended version without changing the original Singleton.


This pattern is often used in situations like logging, managing connections to hardware or databases, caching data, or
handling thread pools, where having just one instance makes sense
Prototype Design Pattern


The prototype pattern is a creational design pattern which is required when object creation is a
time-consuming, and costly operation, so we create objects with the existing object itself to by
copying the existing ones.


The newly copied object may change the same properties only if required.


This approach saves costly resources and time, especially when object creation is a heavy
process.


One of the best available ways to create an object from existing objects is the clone() method.
Clone is the simplest approach to implementing a prototype pattern.


However, it is your call to decide how to copy existing objects based on your business model.
When to use the Prototype Design Pattern


Below is when to use prototype design pattern:

Use the Prototype pattern when creating new objects is more complex or costly than copying existing ones.


Cloning can be more efficient if significant resources are needed.


The Prototype pattern is helpful for managing various objects with minor differences. Instead of creating multiple classes, you
can clone and modify prototypes.


Consider the Prototype pattern for dynamic configurations where you need to create objects at runtime.


You can clone a base configuration and adjust it as necessary.


The Prototype pattern can lower initialization costs, as cloning is often faster than building a new object from scratch,
especially if initialization is resource-intensive.
Builder Method Design Pattern


The Builder Design Pattern is a creational pattern used in software design to
construct a complex object step by step.

It allows the construction of a product in a step-by-step manner, where the
construction process can change based on the type of product being built.

This pattern separates the construction of a complex object from its
representation, allowing the same construction process to create different
representations.
When to use Builder Design Pattern?


The Builder design pattern is used when you need to create complex objects with a large number of optional components or
configuration parameters.

This pattern is particularly useful when an object needs to be constructed step by step, some of the scenarios where the Builder
design pattern is beneficial are:

Complex Object Construction: When you have an object with many optional components or configurations and you want to provide a
clear separation between the construction process and the actual representation of the object.

Step-by-Step Construction: When the construction of an object involves a step-by-step process where different configurations or
options need to be set at different stages.

Avoiding constructors with multiple parameters: When the number of parameters in a constructor becomes too large, and using
telescoping constructors (constructors with multiple parameters) becomes unwieldy and error-prone.

Configurable Object Creation: When you need to create objects with different configurations or variations, and you want a more
flexible and readable way to specify these configurations.

Common Interface for Multiple Representations: When you want to provide a common interface for constructing different
representations of an object.
Determining Object Granularity

Objects can vary tremendously in size and number. They can represent everything down to
the hardware or all the way up to entire applications. How do we decide what should be an
object?

Design patterns address this issue as well. The Facade (185) pattern describes how to
represent complete subsystems as objects, and the Flyweight (195) pattern describes how to
support huge numbers of objects at the finest granularities.

Other design patterns describe specific ways of decomposing an object into smaller objects.

Abstract Factory (87) and Builder (97) yield objects whose only responsibilities are creating
other objects.

Visitor (331) and Command (233) yield objects whose only responsibilities are to implement a
request on another object or group of objects
Specifying Object Implementations

Objects are created by instantiating a class. The object is
said to be an instance of the class.

The process of instantiating a class allocates storage for
the object's internal data (made up of instance variables)
and associates the operations with these data.

A dashed arrowhead line indicates a class that instantiates
objects of another class. The arrow points to the class of the
instantiated objects.

New classes can be defined in terms of existing classes using class inheritance.

When a subclass inherits from a parent class, it includes the definitions of all the data and
operations that the parent class defines.

A mixin class is a class that's intended to provide an optional interface or functionality
to other classes. It's similar to an abstract class in that it's not intended to be
instantiated. Mixin classes require multiple inheritance:
Class versus Interface Inheritance

An object's class defines how the object is implemented.

The class defines the object's internal state and the implementation of its operations. In
contrast, an object's type only refers to its interface—the set of requests to which it can
respond.

An object can have many types, and objects of different classes can have the same type.

An object's class defines how the object is implemented. The class defines the object's
internal state and the implementation of its operations.

In contrast, an object's type only refers to its interface—the set of requests to which it
can respond.

An object can have many types, and objects of different classes can have the same
type.

It's also important to understand the difference between class
inheritance and interface inheritance (or subtyping).

Class inheritance defines an object's implementation in terms
of another object's implementation.

In short, it's a mechanism for code and representation sharing.

In contrast, interface inheritance (or subtyping) describes when
an object can be used in place of another.
Inheritance versus Composition

The two most common techniques for reusing functionality in object-oriented systems are
class inheritance and object composition.

As we've explained, class inheritance lets you define the implementation of one class in terms
of another's. Reuse by subclassing is often referred to as white-box reuse.

The term "white- box" refers to visibility: With inheritance, the internals of parent classes are
often visible to subclasses.

Object composition is an alternative to class inheritance. Here, new functionality is obtained
by assembling or composing objects to get more complex functionality.

Object composition requires that the objects being composed have well-defined interfaces.

This style of reuse is called black-box reuse, because no internal details of objects are visible.

Objects appear only as "black boxes.
Relating Run-Time and Compile-
Time Structures

Consider the distinction between object aggregation and acquaintance and how
differently they manifest themselves at compile- and run-times.Aggregation implies that
one object owns or is responsible for another object.

Generally we speak of an object having or being part of another object.

Aggregation implies that an aggregate object and its owner have identical lifetimes.

Acquaintance implies that an object merely knows of another object. Sometimes
acquaintance is called "association" or the "using" relationship.

Acquainted objects may request operations of each other, but they aren't responsible for
each other.

Acquaintance is a weaker relationship than aggregation and suggests much looser
coupling between objects.

In our diagrams, a plain arrowhead line denotes acquaintance. An
arrowhead line with a diamond at its base denotes aggregation:
Structural Patterns

“In software engineering, structural design patterns are design patterns that
ease the design by identifying a simple way to realize relationships between
entities.”

Structural Patterns describe how objects and classes can be combined to
form structures. We distinguish between object patterns and class patterns.

The difference is that class patterns describe relationships and structures
with the help of inheritance.

Object patterns, on other hand, describe how objects can be associated
and aggregated to form larger, more complex structures.
Adapter Pattern

Also known as Wrapper.

Definition

The Adapter pattern is used to translate the interface of one class into
another interface.

This means that we can make classes work together that couldn't otherwise
because of incompatible interfaces.

A class adapter uses multiple inheritance (by extending one class and/or
implementing one or more classes) to adapt one interface to another. An
object adapter relies on object aggregation.
Where to use

When you want to use an existing class, and its interface does
not match the one you need.

When you want to create a reusable class that cooperates with
unrelated or unforeseen classes, that is, classes that don't
necessarily have compatible interfaces.

When you want to increase transparency of classes.

When you want to make a pluggable kit.
Benefits

Benefits
• Highly class reusable.
•Introduces only one object

Drawbacks/consequences

When using Java, Target must be an interface.
Cont..

In the class-diagram above:

A Client class expects a certain interface (called the
Target interface)

An available interface doesn't match the Target interface

An Adapter class bridges the gap between the Target
interface and the available interface

The available interface is called the Adaptee
Small example

Consider for example a drawing editor that lets users draw and arrange
graphical elements (lines, polygons, text, etc.) into pictures and diagrams.

The drawing editor's key abstraction is the graphical object, which has an
editable shape and can draw itself. 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: a
LineShape class for lines, a PolygonShape class for polygons, and so forth.

Classes for elementary geometric shapes like LineShape and PolygonShape
are rather easy to implement, because their drawing and editing capabilities
are inherently limited.

But a TextShape subclass that can display and edit text is considerably more difficult to implement,
since even basic text editing involves complicated screen update and buffer management.

Meanwhile, an off-the-shelf user interface toolkit might already provide a sophisticated TextView
class for displaying and editing text. Ideally we'd like to reuse TextView to implement TextShape, but
the toolkit wasn't designed with Shape classes in mind.

So we can't use TextView and Shape objects interchangeably.

Instead, we could define TextShape so that it adapts the TextView interface to Shape's. We can do
this in one of two ways:

(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.

These two approaches correspond to the class and object versions of the Adapter pattern. We call
TextShape an adapter.
.
.
Bridge Pattern

Definition

Decouple an abstraction or interface from its
implementation so that the two can vary
independently.

Bridge makes a clear-cut between abstraction and
implementation.
Where to use

When you want to separate the abstract structure and its concrete
implementation.

When you want to share an implementation among multiple objects,

When you want to reuse existing resources in an 'easy to extend'
fashion.

When you want to hide implementation details from clients.

Changes in implementation should have no impact on clients.
Benefits

Implementation can be selected or switched at run-time.

The abstraction and implementation can be independently extended or
composed.

Drawbacks/consequences

Double indirection - In the example, methods are implemented by subclasse of
DrawingAPI class.

Shape class must delegate the message to a DrawingAPI subclass which
implements the appropriate method.

This will have a slight impact on performance.

Consider the implementation of a portable Window abstraction in a user interface
toolkit. This abstraction should enable us to write applications that work on both the X
Window System and IBM's Presentation Manager (PM), for example. Using
inheritance, we could define an abstract class Window and subclasses XWindow and
PMWindow that implement the Window interface for the different platforms
.
Cont..

In the class-diagram above:

Abstraction defines the abstract interface and maintains the
Implementor reference.

Refined Abstraction extends the interface defined by Abstraction.

Implementor defines the interface for implementation classes.

ConcreteImplementor implements the Implementor interface.
Composite Pattern

Definition

The Composite pattern helps you to create tree structures of objects without the need
to force clients to differentiate between branches and leaves regarding usage.

The Composite pattern lets clients treat individual objects and compositions of objects
uniformly.

Where to use

When you want to represent a part-whole relationship in a tree structure.

When you want clients to be able to ignore the differences between compositions of
objects and individual objects.

When the structure can have any level of complexity and is dynamic.
Benefits

Define class hierarchies consisting of primitive objects and composite objects.

Makes it easier to add new kind of components.

Drawbacks/consequences

The Composite pattern makes it easy for you to add new kinds of components
to your collection as long as they support a similar programming interface.

On the other hand, this has the disadvantage of making your system overly
general.

You might find it harder to restrict certain classes where this would normally be
desirable.
...

In the class-diagram above, Component:

is the abstraction for all components, including composite ones,

•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,
and (optional) defines an interface for accessing a component's parent
in the recursive structure, and implements it if that's appropriate.
...

In the class-diagram above, Leaf: represents leaf objects in
the composition, and implements all Component methods.

In the class-diagram above, Composite: represents a
composite Component (component having children),
implements methods
to manipulate children, and implements all Component
methods, generally by delegating them to its children.
Decorator Pattern

Definition

The Decorator pattern lets you attach additional responsibilities and modify an instance
functionality dynamically.

Decorators provide a flexible alternative to subclassing for extending functionality, using
composition instead of inheritance.

Where to use

•When you want to add responsibilities to individual objects dynamically and transparently,
without affecting the original object or other objects.

•When you want to add responsibilities to the object that you might want to change in the
future.

•When extension by static subclassing is impractical.
Benefits

Benefits

More flexibility than static inheritance.

Avoids feature-laden 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 behavior into the object.

Enhances the object's extensibility because you make changes
by coding new classes.
Drawbacks/consequences

Drawbacks/consequences

One thing to keep in mind when implementing the Decorator
pattern is that you need to keep the component interface simple.

You want to avoid making the component interface overly
complex, because a complex interface will make it that much
harder to get each decorator right.

Another potential drawback of the Decorator pattern is the
performance overhead associated with a long chain of decorators.
Motivation
Sometimes we want to add responsibilities to individual objects, not to an entire class. A graphical user
interface toolkit, for example, should let you add properties like borders or behaviors like scrolling to any
user interface
component
Facade Pattern

Definition

This design pattern provides a unified interface to a set of
interfaces in a subsystem.

It defines a higher-level interface that makes the
subsystem easier to use.

A facade is an object that provides a simplified interface
to a larger body of code, such as a class library.
Where to use

The Facade can be used to make a software library easier to use and
understand, since the Facade has convenient methods for common tasks.

For the same reason, it can make code that uses the library more readable.

The pattern can also be used to reduce dependencies of outside code on the
inner workings of a library, since most code uses the Facade it allows more
flexibility when developing the system.

A final usage scenario is where we can wrap several poorly-designed APIs
with a single well-designed API.
Benefits

Benefits

The main benefit with the Facade pattern is that we can combine very complex
method calls and code blocks into a single method that performs a complex and
recurring task.

Besides making code easier to use and understand, it reduces code dependencies
between libraries or packages, making programmers more apt to consideration
before writing new code that exposes the inner workings of a library or a package.

Also, since the Facade makes a weak coupling between the client code and other
packages or libraries it allows us vary the internal components since the client does
not call them directly.
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.
Drawbacks/consequences

Drawbacks/consequences

One drawback is that we have much less control of what goes on
beyond the surface.

Also, if some classes require small variations to the implementation of
Facade methods, we might end up with a mess.

Structure The class diagram of the small example described in the
next section is shown below to illustrate the structure of the Facade
design pattern.
Cont..

Consider the graphics above, where the Client classes makes calls
to the BankAccountFacade class.

The Facade class uses the classes AccountManager,
SecurityManager, AccountReference and BankAccount to perform
the appropriate actions.

By using the Facade pattern we decouple the client code from the
implementation and security details when performing tasks related
to the bank account.
Flyweight Pattern

Definition

Th Flyweight pattern provides a mechanism by which you can avoid creating a large
number of 'expensive' objects and instead reuse existing instances to represent new
ones.

Where to use

•When there is a very large number of objects that may not fit in memory.

•When most of an objects state can be stored on disk or calculated at runtime.

•When there are groups of objects that share state.

•When the remaining state can be factored into a much smaller number of objects
with shared state.
Benefits

Benefits

Reduce the number of objects created, decrease memory
footprint and increase performance.

Drawbacks/consequences

Designing objects down to the lowest levels of system
"granularity" provides optimal flexibility, but can be unacceptably
expensive in terms of performance and memory usage.
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
Flyweights model concepts or entities that are normally too plentiful to represent with objects. For
example, a document editor can create a flyweight for each letter of the alphabet. Each flyweight
stores a character code, but its coordinate position in the document and its typographic style can
be determined from the text layout algorithms and formatting commands in effect wherever the
character appears. The character code is intrinsic
state, while the other information is extrinsic.
Proxy Pattern

Definition

A Proxy is a structural pattern that provides a stand-in for another object in order
to control access to it.

Where to use

When the creation of one object is relatively expensive it can be a good idea to
replace it with a proxy that can make sure that instantiation of the expensive
object is kept to a minimum.

Proxy pattern implementation allows for login and authority checking before one
reaches the actual object that's requested.

Can provide a local representation for an object in a remote location.
Benefits

Benefits

Gives the ability to control access to an object, whether it's because of a
costly creation process of that object or security issues.

Drawbacks/consequences

Introduces another abstraction level for an object, if some objects accesses

the target object directly and another via the proxy there is a chance that

they get different behavior this may or may not be the intention of the
creator.
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.

Consider a document editor that can embed graphical objects in a document.

Some graphical objects, like large raster images, can be expensive to create.

But opening a document should be fast, so we should avoid creating all the
expensive objects at once when the document is opened.

This isn't necessary anyway, because not all of these objects will be visible in
the document at the same time.
Behavioral Design Patterns

“In software engineering, behavioral design patterns are design patterns that
identify common communication patterns between objects and realize these
patterns. By doing so, these patterns increase flexibility in carrying out this
communication.”

Behavioral patterns are patterns that focuses on the interactions between
cooperating objects.

The interactions between cooperating objects should be such that they are
communicating while maintaining as loose coupling as possible.

The loose coupling is the key to n-tier architectures. In this, the implementation and
the client should be loosely coupled in order to avoid hard-coding and
dependencies.
Chain-of-responsibility Pattern

The Chain-of-responsibility pattern lets more than one object handle
a request without mutual knowledge.

We avoid coupling between the sender of a request and the
possible receivers.

We place all receivers in a chain which lets the receiving objects
pass the request along to the next receiver in the
chain until one receiver handles it, or the end of the chain is
reached.
Where to use

When more than one object may handle a request, and the handler isn't known.

When you want to issue a request to one of several objects without specifying the
receiver explicitly.

When the set of objects that can handle a request should be specified dynamically.

Benefits

It reduces coupling.

It increases the flexibility of handling a request.

Drawbacks/consequences

Reception isn't guaranteed since a request has no explicit receiver, there's no
guarantee it will be handled unless the chain is configured properly.

Motivation

Consider a context-sensitive help facility for a graphical user interface. The user can obtain help

information on any part of the interface just by clicking on it. The help that's provided depends
on the

part of the interface that's selected and its context; for example, a button widget in a dialog box
might

have different help information than a similar button in the main window. If no specific help
information

exists for that part of the interface, then the help system should display a more general help
message

about the immediate context—the dialog box as a whole, for example.
Command Pattern

Definition

The Command pattern is used to create objects that represents actions and events in an
application.

A command object encapsulates an action or event and contains all information required to
understand exactly what has happened.

By passing the command object as a parameter we can, anywhere needed extract
information about occurred actions and events.

Where to use

Where you want a action that can be represented in many ways, like drop-
down menu, buttons and popup menu.

To create undo/redo functionality.
Benefits

A command object is a possible storage for procedure parameters.

It can be used while assembling the parameters for a function call and allows the
command to be set aside for later use.

A class is a suitable place to collect code and data related to a specific action or
event.

It allows the reaction to a command to be executed some time after it has occurred.

Command objects enables data structures containing multiple commands.

Command objects supports undo-able operations, provided that the
command objects are stored (for example in a linked list).
Drawbacks/consequences

The main disadvantage of the Command pattern seems to be a
proliferation of little classes that clutter up the program.

However, even in the case where we have separate click events, we
usually call little private methods to carry out the actual function.

It turns out that these private methods are just about as long as our little
classes, so there is frequently little difference in complexity between
building the Command classes and just writing more methods.

The main difference is that the Command pattern produces little
classes that are much more readable.

Motivation

Sometimes it's necessary to issue requests to objects without knowing anything about the
operation being

requested or the receiver of the request. For example, user interface toolkits include objects like
buttons and

menus that carry out a request in response to user input. But the toolkit can't implement the
request explicitly

in the button or menu, because only applications that use the toolkit know what should be done on
which

object. As toolkit designers we have no way of knowing the receiver of the request or the
operations that will

carry it out.
The application configures each MenuItem with an instance of a concrete Command subclass.
When the user selects a MenuItem, the MenuItem calls Execute on its command, and
Execute carries out the operation.
MenuItems don't know which subclass of Command they use. Command subclasses store the
receiver of the request and invoke one or more operations on the receiver.
For example, PasteCommand supports pasting text from the clipboard into a Document.
PasteCommand's receiver is the Document object it is supplied upon instantiation
Iterator Pattern

Definition

The Iterator design pattern provides a way to access the elements of an
aggregate object sequentially without exposing its underlying representation.

Where to use

Use to access the elements of an aggregate object sequentially.

Java's collections like ArrayList and HashMap have implemented the iterator
pattern.
Benefits

The same iterator can be used for different aggregates.

Allows you to traverse the aggregate in different ways depending on your needs.

It encapsulates the internal structure of how the iteration occurs.

•Don't need to bloat the your class with operations for different traversals.

Drawbacks/consequences

Not thread safe unless its a robust iterator that allows insertions and deletions.

This can be be solved by letting the Iterator use a Memento to capture the state
of an iteration.
Mediator Pattern

Definition

With the mediator pattern communication between objects is
encapsulated with a mediator object.

Objects no longer communicate directly with each other, but
instead communicate through the mediator.

This results in a more cohesive implementation of the logic and
decreased coupling between the other objects.
Where to use

The Mediator pattern can be used when a set of objects communicate in
well-specified but complex ways and the resulting inter-dependencies are
unstructured and hard to grasp.

If it is difficult to reuse an object because it refers to and communicates
with many other objects this pattern is a good solution.

Communicating objects' identities will be protected when using the

Mediator pattern which is good when security is important.

Also, if you like to customize some behavior which is spread out between
several classes without a lot of subclassing this pattern should be applied.
...

The pattern is used in many modern systems that reflect a
send/receive protocol, such as list servers and chat rooms.

Another area of use is graphical user interfaces, where the mediator
can encapsulate a collective behavior to control and coordinate the
interactions of a group of GUI widgets.

The mediator serves as an intermediary that keeps objects in the
group from referring to each other explicitly.

The objects only know the mediator which reduces the number of
interconnections.
Benefits

The Mediator pattern has five benefits and drawbacks:
1. Limited subclassing, since a mediator localizes behavior that otherwise would
be distributed among several objects.
Changing some behavior requires us to subclass only the mediator.
2. Colleagues become decoupled which allows us to vary and reuse colleague
and mediator classes independently.
3. A mediator simplifies object protocols since it replaces many-to-many
interactions with one-to-many interactions between the mediator and its
colleagues.

One-to-many interactions are easier to understand, maintain,and extend.
Cont..
4. The mediator abstracts object cooperation.
The mediator lets you focus on how objects interact apart from their
individual behaviors which can help clarify how objects interact in a system.
5. Centralized control is achieved by trading complexity of interaction for
complexity in the mediator.
A mediator encapsulates protocols and can become more complex than any
individual colleague.
This can make the mediator itself a very complex and large piece of code
that is hard to maintain.
Drawbacks/consequences

Drawbacks/consequences


Besides the benefits and drawbacks described above,
one important drawback is that the Mediator pattern
can have a performance impact on a system.


Since all communication must go through the
mediator, it can become a bottleneck.
Often there are dependencies between the
widgets in the dialog. For example, a button
gets disabled
when a certain entry field is empty. Selecting
an entry in a list of choices called a list box
might change
the contents of an entry field.

You can avoid these problems by


encapsulating collective behavior in a
separate mediator object. A
mediator is responsible for controlling and
coordinating the interactions of a group of
objects. The
mediator serves as an intermediary that
keeps objects in the group from referring to
each other explicitly.
The objects only know the mediator, thereby
reducing the number of interconnections.
Small example

Consider a dialog where there are a display label and three buttons: view, book and search.

When clicking the view button it should be disabled and its two colleague buttons should be
enabled.

Also, the display label should change to reflect which button was pressed. We create four
classes ButtonView, ButtonBook, ButtonSearch and LabelDisplay.

Then we let thebutton classes implement an interface Command which allows us to execute the
actions of the buttons from a common interface.

All of these GUI classes are unaware of each other; they should only refer to the mediator. We
now create the Mediator class which holds references to all the GUI objects to control and
coordinate the interactions of these objects. Finally, we create the MediatorExample class to
display the components in a frame. The class implements the ActionListener interface to which
all the buttons should register. The complete source code of this example is shown below:
Memento Pattern

Definition

To record an object internal state without violating encapsulation and reclaim
it later without knowledge of the original object.

A memento is an object that stores a snapshot of the internal state of
another object.

Where to use

When letting some info in an object be available by another object.

When you want to create snapshots of a state for an object.

When you need undo/redo features.
Benefits

Benefits

Ability to restore an object to its previous state.

Drawbacks/consequences

Care should be taken if the originator may change other objects or resources the
memento pattern operates on a single object.

Using memento to store large amounts of data from Originator might be expensive
if clients create and return mementos frequently.

Motivation

Sometimes it's necessary to record the internal state of an object. This is required when
implementing

checkpoints and undo mechanisms that let users back out of tentative operations or recover from
errors.

You must save state information somewhere so that you can restore objects to their previous
states. But

objects normally encapsulate some or all of their state, making it inaccessible to other objects and

impossible to save externally. Exposing this state would violate encapsulation, which can
compromise

the application's reliability and extensibility.
Supporting undo in
this application isn't as
easy as it may seem.
An obvious way to
undo a move
operation is to store
the original distance
moved and move the
object back an
equivalent distance.
In the class-diagram above:

In the class-diagram above:

•An instance from the Originator class is the object that knows
how to save itself. Uses memento to restore itself.

•An instance from the Caretaker class is the object that knows
why and when the Originator needs to save and restore itself.

Never operates or examines the contents of memento An
instance of the Memento class is the lock box that is written and
read by the Originator, and shepherded by the Caretaker.
Cont...

The originator is any object that has an internal state, that we want to
take a snapshot of.

The caretaker is going to do something to the originators state, but wants
to be able to later restore the originators state.

The caretaker first asks the originator for a memento object, containing
the snapshot.

Then it performs the sequence of operations it was going to do.

To roll back to the state before the operations, it returns the memento
object to the originator.
Observer Pattern

Definition

An observer is a structural pattern that enables publish/subscribe functionality.

This is accomplished by an autonomous object, publisher that allows other
objects to attach or detach their subscription as they like.

The pattern does not impose any limit to the number of observers that can attach,
or subscribe, themselves for notification on future changes in the publisher's
state.

Where to use

When an object wants to publish information and many objects will need to
receive that information.
Benefits

Makes for a loose coupling between publisher and subscriber as the publisher
does not need to know who or how many subscribers there will be.

Drawbacks/consequences

In a complex scenario there may be problems to determining whether the
update to the publisher is of relevance to all subscribers or just some of them.

Sending an update signal to all subscribers might impose a communication
overhead of not needed information.
State Pattern

Definition

The State pattern allows an object to alter its behavior when its internal state changes.

By using inheritance and letting subclasses represent different states and functionality we
can switch during runtime.

This is a clean way for an object to partially change its type at runtime.

Where to use

When we need to define a "context" class to present a single interface to the outside world.

By defining a State abstract base class.

When we want to represent different "states" of a state machine as derived classes of the
State base class.
Benefits

Cleaner code when each state is a class instead.

Use a class to represent a state, not a constant.

Drawbacks/consequences

Generates a number of small class objects, but in the process, simplifies and
clarifies the program.

Eliminates the necessity for a set of long, look-alike conditional statements
scattered throughout the code.

Motivation

Consider a class TCPConnection that represents a network connection. A
TCPConnection object can be

in one of several different states: Established, Listening, Closed. When a
TCPConnection object receives

requests from other objects, it responds differently depending on its current state. For
example, the effect

of an Open request depends on whether the connection is in its Closed state or its
Established state. The

State pattern describes how TCPConnection can exhibit different behavior in each state.
Small example
.This example has two states. StateA writes name in lower-case and StateB in
upper-case. We start in state A and then change to state B where we stay for
two calls to writeName before changing back to state A.
Usage example

Consider a drawing application with different tools like select, rectangle,
circle, fill and clear.


Each one of the tool behaves different when you click or drag the mouse
across the screen.


The state of the editor affects the behavior the program should exhibit.


There are some mouse activities which needs to be handled.
Strategy Pattern

Definition

Use strategy when you need to define a family of algorithms, encapsulate each
one, and make them interchangeable.

Strategy lets the algorithm vary independently from clients that use it.

Related patterns include State, Flyweight, Decorator, Composite.

Where to use

When you need to use one of several algorithms dynamically.

When you want to configure a class with one of many related classes (behaviors).

When an algorithm uses data that clients shouldn't know about.
Benefits

Reduces multiple conditional statements in a client.

Hides complex, algorithmic-specific data from the client.

Provides an alternative to subclassing.

•Can be used to hide data that an algorithm uses that clients shouldn't know about.

Drawbacks/consequences

Clients must be aware of different strategies.

A client must understand how strategies differ before it can select the appropriate
one.

Increases the number of objects in an application.
...

In the class-diagram above:

•The Strategy interface defines the behavior that is common to all the

concrete implementations.

•The ConcreteStrategy encapsulates an implementation of a specific

algorithm or behavior that is defined through the Strategy interface.

•The Context provides certain services that is defined by the Strategy

interface and implemented by different ConcreteStrategy classes depending

on behavior.
Small example

This example uses sorting algorithms. Two sorting algorithms (Bubble sort and Quick sort) are
implemented and the client can select either of the algorithms.

The SortInterface describes what the algorithms must be able to do, sort().

The classes QuickSort and BubbleSort both implements the SortInterface and each have their
own algorithm for sorting.

SortingContext maintains a reference to a Strategy object and forwards client requests to the
strategy.

SortingClient set the concrete strategy in the context and invokes the context to run the algorithm.
Usage example

The strategy pattern is used in the implementation of the LayoutManager in
Java.

The LayoutManager can be configured to work with different layout
objects, such as FlowLayout, CardLayout, GridLayout, etc.

These classes encapsulate the actual algorithms for laying out visual
components that the LayoutManager uses to render the interface on the
screen.

By changing the Layout (algorithm) we can dynamically change how the
interface is rendered.

You might also like