Module 2
Module 2
Department of
CSE
Structural Patterns
Design Patterns are of 3 types:
Department of
CSE
Department of BLDEACETInstitute of Technology and
CSE Vijayapur
Structural Patterns
Structural patterns are concerned with how classes and objects are
composed to form larger structures.
Structural class patterns use inheritance to compose interfaces
or implementations.
This pattern is particularly useful for making independently
developed class libraries work together.
Structural object patterns describe ways to compose objects to
realize new functionality.
The added flexibility of object composition comes from the
ability to change the composition at runtime, which is
impossible with static class composition.
Department of
CSE
A common ways to describe a design pattern is the
use of the following template:
1. Pattern Name and Classification
2. Intent
3. Also Known As
4. Motivation (Problem, Context)
5. Applicability (Solution)
6. Structure (a detailed specification of structural
aspects)
7. Participants, Collaborations (Dynamics)
8. Implementation
9. Example
10. Known Uses
11. Consequences
12. Related patterns
Department of
CSE
Pattern Name: Adapter
Intent:
Convert the interface of a class into another interface clients
expect. Adapter lets classes work together that could not
otherwise because of incompatible interfaces.
Collaborations:
Clients call operations on an Adapter instance. In turn, the
adapter calls Adaptee operations that carry out the request.
Department of
CSE
Adapter…
Motivation:
Sometimes a toolkit class that's designed for reuse isn't
reusable only because its interface doesn't match the domain-
specific interface an application requires.
Consider for example a drawing editor that lets users draw and
arrange graphical elements (lines, polygons, text, etc.) into
pictures and diagrams.
The interface for graphical objects is defined by an abstract
class called Shape.
The editor defines a subclass of Shape for each kind of
graphical object.
Classes for elementary geometric shapes are easy to
implement. But a TextShape subclass that can display and edit
text is more difficult to implement. (screen updates, buffer
updates)
Department of
CSE
How can existing and unrelated classes like TextView
work in an application that expects classes with a different
and incompatible interface?
• We could define TextShape so that it adapts the
TextView
interface to Shape's.
1. by inheriting Shape's interface and TextView's
implementation or
2. by composing a TextView instance within a TextShape and
implementing TextShape in terms of TextView's interface.
Department of
CSE
Applicability:
Use the Adapter pattern when
you want to use an existing class, and its interface does
not match the one you need.
you want to create a reusable class that cooperates with
unrelated or unforeseen classes, that is, classes that don't
necessarily have compatible interfaces.
(object adapter only) you need to use several existing
subclasses, but it's impractical to adapt their interface by
subclassing every one. An object adapter can adapt the
interface of its parent class.
Department of
CSE
Department of BLDEACETInstitute of Technology
CSE and Vijayapur
Participants
• Target (Shape)
- defines the domain-specific interface that Client uses.
• Client (DrawingEditor)
- Collaborates with objects conforming to the Target interface.
• Adaptee (TextView)
- defines an existing interface that needs adapting.
• Adapter (TextShape)
- adapts the interface of Adaptee to the Target interface.
Department of
CSE
Collaborations
• Clients call operations on an Adapter instance. In
turn, the adapter calls Adaptee operations that
carry out the request.
Consequences
Class and object adapters have different trade-offs.
A class adapter
• adapts Adaptee to Target by committing to a concrete Adaptee
class. As a consequence, a class adapter won't work when we
want to adapt a class and all its subclasses.
• lets Adapter override some of Adaptee's behavior, since
Adapter
is a subclass of Adaptee.
• introduces only one object, and no additional pointer
indirection
is needed to getDepartment
to
CSE
the adaptee.
of
An object adapter
• lets a single Adapter work with many Adaptees—that is,
the Adaptee itself and all of its subclasses (if any). The Adapter
can also add functionality to all Adaptees at once.
• makes it harder to override Adaptee behavior. It will require
subclassing Adaptee and making Adapter refer to the subclass
rather than the Adaptee itself.
Issues to be consider when using the Adapter pattern:
How much adapting does Adapter do?
Pluggable adapters: describe classes with built-in interface
adaptation.
Using two-way adapters to provide transparency.
Implementation:
Issues to keep in mind while implementing Adapter:
1. Implementing class adapters in C++. Adapter would inherit
publicly from Target and privately from Adaptee.
• Thus adapter would be subtype of target but not of Adaptee
2. Pluggable adapters.
find a "narrow" interface for Adaptee the smallest subset of
operations that lets us do the adaptation.
The narrow interface leads to three implementation
approaches:
a. Using abstract operations.
b. Using delegate objects.
c. Parameterized adapters.
a. Using abstract operations.
b. Using delegate objects.
Department of
CSE
c. Parameterized adapters
• The usual way to support pluggable adapters in Smalltalk is to
parameterize an adapter with one or more blocks.
• The block construct supports adaptation without subclassing.
• A block can adapt a request, and the adapter can store a block
for each individual request.
Department of
CSE
The object adapt uses object composition to
combine classes with different interfaces. In this
approach, the adapterText Shape maintains a
pointer to TextView.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Applicability:
Use the Bridge pattern when
• you want to avoid a permanent binding between an
abstraction and its implementation.
• both the abstractions and their implementations should be
extensible by subclassing.
• changes in the implementation of an abstraction should
have no impact on clients; their code should not have to be
recompiled
• (C++) you want to hide the implementation of an
abstraction completely from clients.
• you have a proliferation of classes as shown earlier in the
first Motivation diagram:- need to use nested generalization
• you want to share an implementation among multiple
objects, and this fact should be hidden from the
client. Department of
CSE
BLDEACETInstitute of Technology
and Vijayapur
Structure:
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Participants :
• Abstraction (Window)
defines the abstraction's interface.
maintains a reference to an object of type Implementor.
• RefinedAbstraction (IconWindow)
- Extends the interface defined by Abstraction.
• Implementor (Windowlmp)
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 Implementor interface provides only primitive
operations, and Abstraction defines higher-level operations
based on these primitives.
• Concretelmplementor (XWindowImp, PMWindowImp)
implements the Implementor interface and defines its
concrete implementation.
Department of BLDEACETInstitute of Technology
CSE and Vijayapur
Collaborations :
• Abstraction forwards client requests to its
Implementor object.
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
Consequences:
The Bridge pattern has the following consequences:
1. Decoupling interface and implementation.
• An implementation is not bound permanently to an
interface.
• The implementation of an abstraction can be configured at
run-time. It's even possible for an object to change its
implementation at run-time.
• Decoupling Abstraction and Implementor
eliminates compile-time dependencies on the
implementation. Does not requires recompiling.
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
Consequences: contd…
2. Improved extensibility.
• You can extend the Abstraction and Implementor
hierarchies independently.
3. Hiding implementation details from clients.
• You can shield clients from implementation details,
like the sharing of implementor objects and the
accompanying reference count mechanism (if any).
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
Implementation:
Consider the following implementation issues when
applying the Bridge pattern:
1. Only one Implementor.
• where there's only one implementation, creating an
abstract Implementor class isn't necessary.
• This is a degenerate case of the Bridge pattern;
there's a one-to-one relationship between
Abstraction and Implementor.
• a change in the implementation o f a class must not
affect its existing clients— that is, they shouldn't have
to be recompiled, just relinked.
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
2. Creating the right Implementor object.
How, when, and where do you decide which Implementor class to
instantiate when there's more than one?
• If Abstraction knows about all Concretelmplementor classes, -
it can decide between them based on parameters passed to
its constructor.
• Example: A collection class supports multiple
implementations based on size of the collection particular
implementation is called
• A linked list implementation can be used for small collections
and a hash table for larger ones.
• Another approach is to choose a default implementation initially
and change it later according to usage.
• It's also possible to delegate the decision to another object
altogether.
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
3. Sharing implementors.
• share implementations among several objects
• The Body stores a reference count that the
Handle class increments and decrements.
4. Using multiple inheritance.
• You can use multiple inheritance in C++ to
combine an interface with its implementation.
• A class can inherit publicly from Abstraction and
privately from a Concretelmplementor.
• But because this approach relies on static inheritance, it
binds an implementation permanently to its interface.
Therefore you can't implement a true Bridge with
multiple inheritance—at least not in C++
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
Sample Code:
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
• Subclasses of Window define the different kinds of
windows the application might use, such as
application windows, icons, transient windows for
dialogs, floating palettes of tools, and so on.
• ApplicationWindow will implement DrawContents to
draw the View instance it stores:
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
DrawRect extracts four coordinates from its two Point
parameters before calling the Windowlmp operation
that draws the rectangle in the window:
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
For Presentation Manager (PM), we define a
PMWindowlmp class:
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
These subclasses implement Windowlmp operations in
terms of window system primitives. For example,
DeviceRect is implemented for X as follows:
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
Known Uses:
• In ET++, WindowImp is called "WindowPort" and has
subclasses such as XWindowPort and SunWindowPort.
• The ET++ Window/WindowPort design extends the Bridge
pattern in that the WindowPort also keeps a reference back
to the Window.
• libg++ defines classes that implement common data
structures, such as Set, LinkedSet, HashSet, LinkedList, and
HashTable.
• NeXT's AppKit uses the Bridge pattern in the implementation
and display of graphical images.
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
Related Patterns:
1. An Abstract Factory can create and configure a
particular Bridge.
2. The Adapter pattern is geared toward making
unrelated classes work together.
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
COMPOSITE : Object Structural patterns
Intent:
• Compose objects into tree structures to represent part-
whole hierarchies.
• Composite lets clients treat individual objects and
compositions of objects uniformly.
Motivation:
• Graphics applications like drawing editors and schematic
capture systems let users build complex diagrams out of
simple components.
• Example
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
Problem:
• Code that uses these classes must treat primitive and container
objects differently,
• Even if most of the time the user treats them identically.
Having to
distinguish these objects makes the application more complex.
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
Solution:
The Composite pattern describes how to use recursive
composition so that clients don't have to make this distinction.
• The key to the Composite pattern is an abstract class (Graphic) that
represents both primitives and their containers.
• Graphic declares operations like Draw that are specific to graphical
objects.
• It also declares operations that all composite objects share, such as
operations for accessing and managing its children.
• The subclasses Line, Rectangle, and Text define primitive graphical
objects.
• Since primitive graphics have no child graphics, none of these
subclasses implements child-related operations.
• The Picture class defines an aggregate of Graphic objects.
• Because the Picture interface conforms to the Graphic interface,
Picture objects can compose other Pictures recursively.
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
The following diagram shows a typical composite
object structure of recursively composed Graphic
objects:
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
Applicability:
Use the Composite pattern when
• you want to represent part-whole hierarchies of
objects.
• you want clients to be able to ignore the difference
between compositions of objects and individual
objects. Clients will treat all objects in the composite
structure uniformly.
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
Structure:
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
A typical Composite object structure might look
like this:
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
Participants:
• Component (Graphic)
declares the interface for objects in the composition.
implements default behavior for the interface common to all classes, as
appropriate.
declares an interface for accessing and managing its child components.
(optional) defines an interface for accessing a component's parent in the
recursive structure, and implements it if that's appropriate.
• Leaf (Rectangle, Line, Text, etc.)
represents leaf objects in the composition. A leaf has no children.
defines behavior for primitive objects in the composition.
• Composite (Picture)
defines behavior for components having children.
stores child components.
implements child-related operations in the Component interface.
• Client
manipulates objects in the composition through the Component
interface. Department of BLDEACETInstitute of Technology
CSE and Vijayapur
Collaborations:
• Clients use the Component class interface to interact
with objects in the composite structure.
• If the recipient is a Leaf, then the request is handled
directly.
• If the recipient is a Composite, then it usually
forwards
requests to its child components,
• possibly performing additional operations before
and/or after forwarding.
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
Consequences:
I. Defines class hierarchies
• Defines class hierarchies consisting of primitive objects and
composite objects.
• Primitive objects can be composed into more complex objects,
which in turn can be composed, and so on recursively.
• Wherever client code expects a primitive object, it can also take a
composite object.
II. makes the client simple.
• Clients can treat composite structures and individual objects
uniformly.
• Clients normally don't know (and shouldn't care)whether they're
dealing with a leaf or a composite component.
• This simplifies client code, because it avoids having to write tag-
and-case-statement-style functions over the classes that define
the composition.
Department
Departmentof
of BLDEACETInstitute of Technology
CSE
CSE and Vijayapur
Consequences:
III. makes it easier to add new kinds o f components.
• Newly defined Composite or Leaf subclasses work automatically
with existing structures and client code.
• Clients don't have to be changed for new Component classes.
IV. can make your design overly general.
• The disadvantage of making it easy to add new
components is
that it makes it harder to restrict the components of a composite.
• Sometimes you want a composite to have only certain
components.
• With Composite, you can't rely on the type system to enforce
those constraints for you.
• You'll have to use run-time checks instead.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Implementation:
There are many issues to consider when implementing the Composite
pattern:
1. Explicit parent references.
2. Sharing components.
3. Maximizing the Component interface.
4. Declaring the child management operations.
5. Should Component implement a list of Components?
6. Child ordering.
7. Caching to improve performance.
8. Who should delete components?
9. What's the best data structure for storing components?
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Implementation: Contd…
1. Explicit parent references.
• Maintaining references from child components to their parent can
simplify the traversal and management.
• The parent reference simplifies moving up the structure and deleting a
component.
• Parent references also help support the Chain of Responsibility (223)
pattern.
• Usually parent reference defined in the Component class.
• Leaf and Composite classes can inherit the reference and the operations
that manage it.
• With parent references, it's essential to maintain the invariant of all
children.
• The easiest way to ensure this is to change a component's parent only
when it's being added or removed from a composite.
• If this can be implemented once in the Add and Remove operations of
the Composite class, then it can be inherited by all the subclasses, and
the invariant will be maintained automatically.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
2. Sharing components.
• Useful to share components for ex, to reduce storage
requirements.
• when a component can have no more than one parent, sharing
components becomes difficult.
• Solution:
• children to store multiple parents :- But this can
lead to ambiguities as a request propagates up the
structure.
• The Flyweight(195) pattern shows how to rework a
design
to avoid storing parents altogether
• children can avoid sending parent requests by
externalizing
some or all of their state.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
3. Maximizing the Component interface.
• Goals of the Composite pattern is to make clients unaware of
the specific Leaf or Composite classes they're using.-> This
could be achieved by defining more common operations
for Composite and Leaf classes as possible.
• The Component class usually provides default
implementations for these operations, and Leaf and
Composite subclasses will override them.
• This sometimes makes operations to be defined that doesn't
make sense for subclasses.
• Define a default operation for child access in the Component
class that never returns any children.
• Leaf classes can use the default implementation, but
Composite classes will reimplement it to return their
children.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
4. Declaring the child management operations.
• The Composite class implements the Add and Remove operations for
managing children,
• An important issue in the Composite pattern is which classes declare
these operations in the Composite class hierarchy.
• Should we declare these operations in the Component and make them
meaningful for Leaf classes, or should we declare and define them only
in Composite and its subclasses?
The decision involves a trade-off between safety and transparency:
1. Defining the child management interface at the root of the class
hierarchy gives you transparency, bcz you can treat all components
uniformly.=> It costs you safety, because clients may try to do
meaningless things like add and remove objects from leaves.
2. Defining child management in the Composite class gives you safety,
because any attempt to add or remove objects from leaves will be
caught at compile-time in a statically typed language like C++. =>But it
lose transparency, because leaves and composites have different
interfaces.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
• One approach is to declare an operation Composite
*GetComposite ( ) in the Component class.
• Component provides a default operation that returns a null
pointer.
• The Composite class redefines this operation to return itself
through the this pointer:
Department
Departmentof
of CSE BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
Vijayapur
CSE and Vijayapur
5. Should Component implement a list of Components?
• Usually we define the set of children as an instance variable
in the Component class where the child access and
management operations are declared.
• But putting the child pointer in the base class incurs a space
penalty for every leaf, even though a leaf never has children.
• This is worthwhile only if there are relatively few children in
the structure.
• That is have few children
Department
Departmentof
of BLDEACETof Technology
BLDEACETInstitute and
of Technology
CSE
CSE and Vijayapur
Vijayapur
6. Child ordering.
• Many designs specify an ordering on the children of Composite.
• Graphics example, ordering may reflect front-to-back ordering.
• If Composites represent parse trees, then compound
statements can be instances of a Composite whose children
must be ordered to reflect the program.
• When child ordering is an issue, one must design child access
and management interfaces carefully to manage the sequence
of children.
• The Iterator ( 257)pattern can guide you in this.
7. Caching to improve performance.
• To traverse or search compositions frequently, the Composite
class
can cache traversal or search information about its children.
• The Composite can cache actual results or just information
that lets
it short-circuit the traversal or search.
• Changes to a component will require invalidating the caches
of its Department
Departmentof
CSE
CSE
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
and Vijayapur
Vijayapur
Technologyand
8. Who should delete components?
• In languages without garbage collection, it's usually best to
make a Composite responsible for deleting its children when
it's destroyed.
• An exception to this rule is when Leaf objects are immutable
and thus can be shared.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
• Subclasses of Equipment might include Leaf classes that
represent disk drives, integrated circuits, and switches:
CompositeEquipment
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
A default implementation of NetPrice might
use Createlterator to sum the net prices of the
subequipment.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Known Uses
• The original View class of Smalltalk Model/View/Controller [
KP88] was a Composite,
• User interface toolkits and frameworks
• ET++, Interviews, Graphics, Glyphs
Related Patterns
• Chain of Responsibility (223).
• Decorator ( 175 ) : When decorators and composites are
used together, they will usually have a common parent class.
So decorators will have to support the Component interface
with operations like Add, Remove, and GetChild.
• Flyweight ( 195) lets you share components, but they can no
longer refer to their parents.
• Iterator (257)can be used to traverse composites.
• Visitor( 331) localizes operations and behavior that would
otherwise be distributed across Composite and Leaf classes.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
DECORATOR: an Object structural pattern
• Intent:
Attach additional responsibilities to an object
dynamically.
Decorators provide a flexible alternative to subclassing
for extending functionality.
• Also Known As
Wrapper
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
• Motivation:
Sometimes want to add responsibilities
we
individual objects,tonot to an entire class.
A graphical interface toolkit, for example,
user
should let you add properties like borders or
behaviors like scrolling to any user interface
component.
One way to add responsibilities is with inheritance
Inheriting a border from another class puts a border
around every subclass instance. This is inflexible,
because the choice of border is made statically.
A client can't control how and when to decorate the
component with a border.
A more flexible approach is to enclose the
component in
another object that adds the border. The enclosing object
is called a decorator.
Department
Departmentof
CSE
CSE
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
and Vijayapur
Vijayapur
Technologyand
• The decorator conforms to the interface of the component
it decorates so that its presence is transparent to the
component's clients.
• The decorator forwards requests to the component and
may perform additional actions (such as drawing a border)
before or after forwarding.
• Transparency lets you nest decorators recursively, thereby
allowing an unlimited number of added responsibilities.
Example: The following object diagram shows how
to compose a TextView object with BorderDecorator and
ScrollDecorator objects to produce a bordered, scrollable
text view:
Department
Departmentof
of CSE BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
Vijayapur
CSE and Vijayapur
The ScrollDecorator and BorderDecorator classes
are subclasses of Decorator, an abstract class for
visual components that decorate other visual
components.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Applicability
Use Decorator
•to add responsibilities to individual objects dynamically
and transparently, that is, without affecting other
objects.
• for responsibilities that can be withdrawn.
• when extension by subclassing is impractical.
Sometimes a large number of
independent extensions are possible and
would produce an explosion of subclasses to
support ever y combination.
Or a class definition maybe hidden
or otherwise unavailable for subclassing.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Structure
Department
Departmentof
of CSE BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
Vijayapur
CSE and Vijayapur
Participants
• Component (VisualComponent)
- defines the interface for objects that can have
responsibilities added to them dynamically.
• ConcreteComponent (TextView)
- defines an object to which additional responsibilities can
be attached.
• Decorator
- maintains a reference to a Component object and
defines an interface that conforms to Component's
interface.
• ConcreteDecorator (BorderDecorator,
ScrollDecorator)
- adds responsibilities to the component.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Collaborations
• Decorator forwards requests to its
Component object.
• It may optionally perform additional
operations before and after forwarding the
request.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Consequences
The Decorator pattern has at least two key benefits and two
liabilities:
1. More flexibility than static inheritance.
The Decorator pattern provides a more flexible way to add
responsibilities to objects
With decorators, responsibilities can be added and
removed at run-time simply by attaching and detaching
them.
In contrast, inheritance requires creating a new class for
each additional responsibility:- Which increases number
of classes and complexity of a system
Providing different Decorator classes for a specific
Component class lets you mix and match responsibilities.
Decorators also make it easy to add a property twice
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
2. Avoids feature-laden classes high up in the hierarchy
Decorator offers a pay-as- you-go approach to adding
responsibilities.
Define a simple class and add functionality incrementally
with Decorator objects.
Functionality can be composed from simple pieces. A s a
result, an application needn't pay for features it doesn't
use.
Easy to define new kinds of Decorators independently
from the classes of objects they extend, even for
unforeseen extensions.
Extending a complex class tends to expose details of
responsibilities
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
3. A decorator and its component aren't identical.
A decorator acts as a transparent enclosure.
From object identity point of view, a decorated
component is not identical to the component itself.
Shouldn't rely on object identity when you use
decorators.
4. Lots of little objects.
A design that uses Decorator often results in
systems composed of lots of little objects that all
look alike.
The objects differ only in the way they are
interconnected, not in their class or in the value of
their variables.
These systems are easy to customize, but can be
hard to learn and debug.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Implementation
Several issues should be considered when applying the
Decorator pattern:
1. Interface conformance.
2. Omitting the abstract
3. Keeping Component classes lightweight.
4. Changing the skin of an object versus changing
its guts
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
1. Interface conformance.
A decorator object's interface must conform to
the interface of the component it decorates.
ConcreteDecorator classes must therefore
inherit from a common class (at least in C++).
2. Omitting the abstract Decorator class.
No need to define an abstract Decorator class when
only need to add one responsibility.
Dealing with an existing class hierarchy rather than
designing a new one.=> can merge Decorator's
responsibility for forwarding requests to the
component into the ConcreteDecorator.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
3. Keeping Component classes lightweight
Keep the common class lightweight; that is, it should focus on
defining an interface, not on storing data.
The definition of the data representation should be deferred to
subclasses;
Otherwise the complexity of the Component class might make the
decorators too heavyweight.
Putting a lot of functionality into Component also increases the
probability that concrete subclasses will pay for features they don't
need.
4. Changing the skin of an object versus changing its guts
A decorator as a skin over an object that changes its behavior.
An alternative is to change the object's guts. Ex: Strategy ( 315)
pattern for changing the guts.
Since the Decorator pattern only changes a component from the
outside, the component doesn't have to know anything about its
decorators; that is, the decorators are transparent to the
component: Department
Departmentof
CSE
Vijayapur
of CSE BLDEACETInstitute
BLDEACETInstituteof
and Vijayapur
ofTechnology
Technologyand
With strategies, the component itself knows about possible
extensions. So it has to reference and maintain the corresponding
strategies:
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Sample Code
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
For each operation in
VisualComponent's interface,
Decorator defines a default
implementation
that passes the request on to -
component:
Subclasses of Decorator define specific decorations
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Known Uses
Many object-oriented user interface toolkits use
decorators to add graphical embellishments to
widgets.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
The Decorator pattern gives us an elegant way to add
these responsibilities to streams. The diagram below
shows one solution to the problem:
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Related Patterns
Adapter ( 139) :
A decorator is different from an adapter in that a decorator
only changes an object's responsibilities, not its interface;
an adapter will give an object a completely new interface.
Composite ( 163) :
A decorator can be viewed as a degenerate composite with
only one component.
However, a decorator adds additional responsibilities—it
isn't intended for object aggregation.
Strategy (315) :
A decorator lets you change the skin of an object;
a strategy lets you change the guts. These are two
alternative ways of changing an object.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
FACADE : Objects structural patterns
Intent
Provide a unified interface to a set of interfaces in a subsystem.
Facade defines a higher-level interface that makes the subsystem
easier to use.
Motivation
• Structuring a system into subsystems helps reduce complexity. A
common design goal is to minimize the communication and
dependencies between subsystems.
• One way to achieve this goal is to introduce a facade object that
provides a single, simplified interface to the more general facilities
of a subsystem.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
• Example : a programming environment that gives applications
access to its compiler subsystem. This subsystem contains classes
such as Scanner,Parser, ProgramNode, BytecodeStream, and
ProgramNodeBuilder that implement the compiler.
• Most clients of a compiler generally don't care about details like
parsing and code generation; they merely want to compile some
code
• To provide a higher-level interface that can shield clients from
these classes, the compiler subsystem also includes a Compiler
class=> defines a unified interface to the compiler's
functionality.
• The Compiler class acts as a façade=>
Offers clients a single, simple interface to the compiler
subsystem.
It glues together the classes that implement compiler
functionality without hiding them completely
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Applicability
Use the Façade pattern when
1. You want to provide a simple interface to a complex subsystem
Subsystems often get more complex as they evolve.
Most patterns, when applied, result in more and smaller
classes.
This makes the subsystem more reusable and easier to
customize, but it also becomes harder to use for clients that
don't need to customize it.
A facade can provide a simple default view of the
subsystem
that is good enough for most clients.
Only clients needing more customizability will need to look
beyond the facade.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
2. Many dependencies between clients and the
implementation classes of an abstraction.
Introduce a facade to decouple the
subsystem from clients
and other subsystems,
Thereby promoting subsystem
independence and
portability.
3. You want to layer your subsystems.
Use a facade to define an entry point to each subsystem
level.
If subsystems are dependent, then you can simplify the
dependencies between them by making them
communicate with each other solely through their
facades.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Structure
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Participants
• Facade (Compiler)
- knows which subsystem classes are responsible for a request.
- delegates client requests to appropriate subsystem objects.
• subsystem classes (Scanner, Parser, ProgramNode, etc.)
- implement subsystem functionality.
- handle work assigned by the Facade object.
- have no knowledge of the facade; that is they keep no references to
it.
Collaborations
• Clients communicate with the subsystem by sending requests to
Facade,
• Which forwards them to the appropriate subsystem object(s).
• Although the subsystem objects perform the actual work, the facade
may have to do work of its own to translate its interface to subsystem
interfaces.
• Clients that use the facade don't have to access its subsystem objects
directly. Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Consequences
The Facade pattern offers the following benefits:
1.It shields clients from subsystem components, thereby reducing
the number of objects that clients deal with and making the
subsystem easier to use.
2.It promotes weak coupling between the subsystem and its clients.
Often the components in a subsystem are strongly coupled.
Weak coupling lets you vary the components of the subsystem
without affecting its clients.
3.It doesn't prevent applications from using subsystem classes if they
need to. Thus you can choose between ease of use and generality.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Implementation
Consider the following issues when implementing a facade:
1. Reducing client-subsystem coupling.
• The coupling between clients and the subsystem can be reduced
even.
• Make Facade an abstract class with concrete subclasses for
different implementations of a subsystem.
• Then clients can communicate with the subsystem through the
interface of the abstract Facade class.
• This abstract coupling keeps clients from knowing which
implementation of a subsystem is used.
• An alternative to subclassing is to configure a Facade object with
different subsystem objects.
• To customize the facade, simply replace one or more of its
subsystem objects.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
2. Public versus private subsystem classes
• A subsystem is analogous to a class => both have
interfaces, and both encapsulate something—
• a class encapsulates state and operations,
• while a subsystem encapsulates classes.
• Just as similar to public and private interfaces,
consider
public and private interfaces to subsystems.
• The public interface to a subsystem consists of classes
that all clients can access; the private interface is just
for subsystem extenders.
• The Facade class is part of the public interface,
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Sample Code
The Scanner class takes a stream of characters and produces a
stream of tokens, one token at a time.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Parser calls back on ProgramNodeBuilder to build the parse
tree incrementally. These classes interact according to the
Builder (97) pattern.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
The parse tree is made up of instances of ProgramNode
subclasses such as StatementNode, ExpressionNod e, and
so forth
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Known Uses
• The compiler example in the Sample Code section was
inspired by the Object- Works\Smalltalk compiler system
• In the ET++ application framework=> an application can
have built-in browsing tools for inspecting its objects at
run-time. These browsing tools are implemented in a
separate subsystem that includes a Facade class called
"ProgrammingEnvironment.“
• The Choices operating system=> uses facades to compose
many frameworks into one. The key abstractions in
Choices are processes, storage, and address spaces.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Related Patterns
Abstract Factory ( 87)
can be used with Facade to provide an interface for creating
subsystem objects in a subsystem-independent way.
Abstract Factory can also be used as an alternative to Facade to
hide platform-specific classes.
Mediator (273) is similar to Façade.
Mediator's purpose is to abstract arbitrary communication
between colleague objects, often centralizing functionality that
doesn't belong in any one o f them.
A mediator's colleagues are aware of and communicate with the
mediator instead of communicating with each other directly.
In contrast, a façade merely abstracts the interface to subsystem
objects to make them easier to use;
It doesn't define new functionality, and subsystem classes don't
know about it.
Thus Facade objects are often Singletons(127).
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
FLYWEIGHT is a Object structural Pattern:
Intent :
Use sharing to support large numbers of fine-grained objects
efficiently.
Motivation :
Some applications could benefit from using objects throughout their
design, but a naive implementation would be prohibitively expensive.
For example, Document editor implementations have text formatting
and editing facilities that are modularized to some extent.
Object-oriented document editors typically use objects to represent
embedded elements like tables and figures.
Uses an object for each character in the document=>Promotes
flexibility at
the finest levels in the application.
Characters and embedded elements could then be treated uniformly with
respect to how they are drawn and formatted.
The application could be extended to support new character sets without
disturbing other functionality.
structure.
The application's object structure could mimic the document's physical
Department
Departmentof
of CSE BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE and Vijayapur
Vijayapur
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.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
A flyweight is a shared object that can be used in multiple
contexts simultaneously.
The flyweight acts as an independent object in each context—it's
indistinguishable from an instance of the object that's not shared.
Flyweights cannot make assumptions about the context in which
they operate.
The key concept is the distinction between intrinsic and
extrinsic
state.
Intrinsic state is stored in the flyweight; it consists of
information that 's independent of the flyweight's context,
making it sharable.
Extrinsic state depends on and varies with the flyweight's
context and therefore can't be shared.
Client objects are responsible for passing extrinsic state to the
flyweight when it needs it.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
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.
Logically there is an object for every occurrence of a given
character in the document
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Physically, there is one shared flyweight object per
character,
It appears in different contexts in the document
structure.
Each occurrence of a particular character object refers to
the same instance in the shared pool of flyweight objects:
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Class Structure
Glyph is the abstract class
for graphical objects, some
of which may be flyweights.
Operations that may
depend on extrinsic state
have it passed to them as a
parameter.
For example, Draw and
Intersects must know whic h
context the glyph is in
before they can do their
job.
A flyweight representing the letter "a" only stores the corresponding character
code;
it doesn't need to store its location or font.
Clients supply the context dependent information that the flyweight needs to
draw itself
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Applicability:
Apply the Flyweight pattern when all of the following are
true:
• An application uses a large number of objects.
• Storage costs are high because of the sheer quantity of
objects.
• Most object state can be made extrinsic.
•Many groups of objects may be replaced by relatively few shared
objects once extrinsic state is removed.
•The application doesn't depend on object identity. Since flyweight
objects may be shared, identity tests will return true for
conceptually distinct objects.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Structure
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
The following diagram shows how the flyweights are shared:
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Participants
1. Flyweight (Glyph)
declares an interface through which flyweights can receive and act on
extrinsic state.
2. ConcreteFlyweight (Character)
implements the Flyweight interface and adds storage for intrinsic
state, if
any.
A ConcreteFlyweight object must be sharable.
Any state it stores must be intrinsic; it must be independent of the
ConcreteFlyweight object's context.
3. UnsharedConcreteFlyweight (Row ,Column)
not all Flyweight subclasses need to be shared.
The Flyweight interface enables sharing; it doesn't enforce it.
It's common for UnsharedConcrete- Flyweight objects to have
ConcreteFlyweight objects as children at some level in the flyweight
object structure (as the Row and Column classes have).
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Participants contd…
4. FlyweightFactory
creates and manages flyweight objects.
ensures that flyweights are shared properly. When a client requests
a flyweight,
the FlyweightFactory object supplies an existing instance or creates
one, if none exists.
5. Client
maintains a reference to flyweight(s).
computes or stores the extrinsic state of flyweight(s).
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Collaborations
State that a flyweight needs to function must be characterized
as either intrinsic or extrinsic.
Intrinsic state is stored in the ConcreteFlyweight object;
Extrinsic state is stored or computed by Client objects.
Clients pass this state to the flyweight when they invoke its
operations.
• Clients should not instantiate ConcreteFlyweights directly.
• Clients must obtain ConcreteFlyweight objects exclusively from
the FlyweightFactory object to ensure they are shared properly.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Consequences
Flyweights may introduce run-time costs associated with
transferring, finding, and/or computing extrinsic state, especially if
it was formerly stored as intrinsic state.
such costs are offset by space savings, which increase as more
flyweights are shared.
Storage savings are a function of several factors:
• The reduction in the total number of instances that comes
from
sharing
• The amount of intrinsic state per object
• Whether extrinsic state is computed or stored.
The more flyweights are shared, the greater the storage savings.
The
savings increase with the amount of shared state.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Implementation
Consider the following issues when implementing the Flyweight
pattern:
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
1. Removing extrinsic state.
• Removing extrinsic state won't help reduce storage costs if there
are as many different kinds of extrinsic state as there are objects
before sharing.
• Ideally, extrinsic state can be computed from a separate object
structure, one with far smaller storage requirements.
• for example, we can store a map of typographic information
in a
separate structure rather than store the font and type style with
each character object.
• When a character draws itself, it receives its typographic
attributes
as a side-effect of the draw traversal
• Storing this information externally to each character object is far
more efficient than storing it internally.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
2. Managing shared objects.
• Because objects are shared, clients shouldn't instantiate them
directly.
• FlyweightFactory lets clients locate a particular flyweight.
• FlyweightFactory objects often use an associative store to let
clients look up flyweights of interest.
• For example, the flyweight factory in the document editor can
keep a table of flyweights indexed by character codes.
• The manager returns the proper flyweight given its code,
creating the flyweight if it does not already exist.
• Sharability also implies some form of reference counting or
garbage collection to reclaim a flyweight's storage when it's no
longer needed.
• If the number of flyweights is fixed and small=>
flyweights are worth keeping around permanently.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Sample Code
• Logically, glyphs (base class )are Composites that have
graphical attributes and can draw themselves.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
The Character subclass just stores a character code:
• To keep from allocating space for a font attribute in every glyph, we'll
store the attribute extrinsically in a GlyphContext object.
• GlyphContext acts as a repository of extrinsic state.
• Any operation that needs to know the glyph's font in a given context
will
have a GlyphContext instance passed to it as a parameter. The
• operation can then query the GlyphContext for the font in that
context.
• The context depends on the glyph's location in the glyph structure.
• Therefore Glyph's child iteration and manipulation operations must
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
update the GlyphContext
CSE
CSE whenever they're
and Vijayapur
Vijayapur used.
• GlyphContext must be kept informed of the current position in the glyph
structure during traversal.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Consider the following excerpt from a glyph composition:
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
The BTree structure for font information might look like
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
For example, assuming we're at index 102 in the traversal, the
following code sets the font of each character in the word
"expect" to that of the surrounding text (that is, times12, an
instance of Font for 12-point Times Roman):
Department
Departmentof
of CSE BLDEACETInstituteTechnology
of Technology
and
BLDEACETInstitute
CSE of and Vijayapur Vijayapur
Class Glyph Factory instantiates Character and
other kinds of glyphs.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Known Uses
1. Interviews 3.0:
• Its developers built a powerful document editor called Doc as a
proof of concept [CL92]. Doc uses glyph objects to represent
each character in the document.
• Only position is extrinsic, making Doc fast. Documents are
represented by a class Document, which also acts as the
FlyweightFactory.
2. ET++:
• uses flyweights to support look-and-feel independence.
• The look-and-feel standard affects the layout of user
interface
elements.
• A widget delegates all its layout and drawing behavior to a
separate Layout object. Changing the Layout object changes the
look and feel, even at run-time.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Related Patterns
• The Flyweight pattern is often combined with the Composite
( 163) pattern to implement a logically hierarchical structure
in terms of a directed-acyclic graph with shared leaf nodes.
• It's often best to implement State (305) and Strategy
(315) objects as flyweights
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
PROXY: a Object Structural pattern
Intent
Provide a surrogate or placeholder for another object to control
access to it.
Also Known As
Surrogate
Motivation
• One reason for controlling access to an object is to defer the full
cost of its creation and initialization until we actually need to use it.
• Example: 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.
• Because not all of these objects will be visible in the document at
the same time.
• creating each expensive object on demand, which in this case
Department
Departmentofof CSE BLDEACETInstitute
BLDEACETInstituteof
ofTechnology
Technologyand
occurs when an image
CSE
Vijayapur becomes andvisible.
Vijayapur
Solution: an image proxy, that acts as a stand-in for
the real image. The proxy acts just like the image and takes care
of instantiating it when it's required.
• The image proxy creates the real image only when the document
editor asks it to display itself by invoking its Draw operation.
• The proxy forwards subsequent requests directly to the image. It
must therefore keep a reference to the image after creating it.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
• Let's assume that images are stored in separate files.
• we can use the file name as the reference to the real object.
• The proxy also stores its extent, that is, its width and height.
• The extent lets the proxy respond to requests for its size from
the formatter without actually instantiating the image.
Department
Departmentof
of CSE BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
Vijayapur
CSE and Vijayapur
• The document editor accesses embedded images through the
interface defined by the abstract Graphic class.
• ImageProxy is a class for images that are created on demand.
• ImageProxy maintains the file name as a reference to the image
on disk.
• The file name is passed as an argument to the ImageProxy
constructor.
• ImageProxy also stores the bounding box of the image and a
reference to the real Image instance.
• This reference won't be valid until the proxy instantiates the
real
image.
• The Draw operation makes sure the image is instantiated
before
forwarding it the request.
• GetExtent forwards the request to the image only if it's
instantiated; otherwise
CSE
CSE ImageProxy
Department
Departmentof
of
returns
BLDEACETInstitute
the extent it stores.
BLDEACETInstituteofofTechnology
and Vijayapur
Vijayapur
Technologyand
Applicability
Proxy is applicable whenever there is a need for a more versatile
or sophisticated reference to an object than a simple pointer.
Common situations in which the Proxy pattern is applicable:
1. A remote proxy provides a local representative for an object in a
different address space. NEXTSTEP [Add 94]uses the class NXProxy for
this purpose. Coplien [Cop 92]calls this kind of proxy an "Ambassador.“
2. A virtual proxy creates expensive objects on demand.
3. A protection proxy controls access to the original object. Protection
proxies are useful when objects should have different access rights.
Ex: KernelProxies in the Choices operating system [CIRM93] provide
protected access to operating system objects.
4. A smart reference is a replacement for a bare pointer that performs
additional actions when an object is accessed. Typical uses include
• Counting the number of references to the real object so that it can be
freed
automatically when there are no more references.
• Loading a persistent object into memory when it's first referenced.
• Checking
no other that the real object
Department of isBLDEACETInstitute
locked beforeofit's
BLDEACETInstitute accessed
ofTechnology
Technologyand to ensure that
CSE and Vijayapur
Vijayapur
Structure
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Participants
1. Proxy (ImageProxy)
• maintains a reference that lets the proxy access the real subject.
Proxy may refer to a Subject if the RealSubject and Subject
interfaces are the same.
• Provides an interface identical to Subject's so that a proxy can
by
substituted for the real subject.
• Controls access to the real subject and may be responsible for
creating and deleting it.
Other responsibilities depend on the kind of proxy:
• remote proxies are responsible for encoding a request and its
arguments and for sending the encoded request to the real subject in
a different address space.
• virtual proxies may cache additional information about the real
subject so that they can postpone accessing it. For example, the
ImageProxy from the Motivation caches the real image's extent.
• protection proxies check that the caller has the access
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
permissions CSE
CSE and Vijayapur
Vijayapur
2. Subject (Graphic)
• Defines the common interface for RealSubject and
Proxy so that a Proxy can be used anywhere a
RealSubject is expected.
3. RealSubject (Image)
• defines the real object that the proxy represents.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Collaborations
• Proxy forwards requests to RealSubject when appropriate,
depending on the kind of proxy.
Consequences
The Proxy pattern introduces a level of indirection when accessing
an object. The additional indirection has many uses, depending on
the kind of proxy:
1. A remote proxy can hide the fact that an object resides in a different
address space.
2. A virtual proxy can perform optimizations such as creating an object on
demand.
3. Both protection proxies and smart references allow additional
housekeeping tasks when an object is accessed.
There's another optimization that the Proxy pattern can hide from the
client. It's called copy-on-write , and it's related to creation on demand.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
• There's another optimization that the Proxy pattern can hide from
the client. It's called copy-on-write, and it's related to creation on
demand.
• Copying a large and complicated object can be an expensive
operation.
• If the copy is never modified, then there's no need to incur this
cost.
• By using a proxy to postpone the copying process, we ensure that
we pay the price of copying the object only if it's modified.
• To make copy-on-write work, the subject must be reference
counted.
• Copying the proxy will do nothing more than increment this
reference count. Only when the client requests an operation that
modifies the subject does the proxy actually copy it.
• In that case the proxy must also decrement the subject's
reference
count.
• When the reference countofofgoesBLDEACETInstitute
Department
Department to zero, the ofsubject
BLDEACETInstitute gets
ofTechnology
Technologyand deleted.
CSE
CSE and Vijayapur
Vijayapur
Implementation
The Proxy pattern can exploit the following language features:
1. Overloading the member access operator in C++.
2. Using doesNotUnderstand in Smalltalk
3. Proxy doesn't always have to know the type of real subject.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
1. Overloading the member access operator in C++.
•C++ supports overloading operator->, the member access operator.
Overloading this operator lets you perform additional work
whenever an object is dereferenced.
• use this technique to implement a virtual proxy called ImagePtr.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
The overloaded -> and * operators use Loadlmage to return
_image to callers (loading it if necessary).
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
2. Using doesNotUnderstand in Smalltalk
• Smalltalk calls doesNotUnderstand: aMessage when a client
sends a message to a receiver that has no corresponding
method.
• The Proxy class can redefine doesNotUnderstand so that the
message is forwarded to its subject.
• To ensure that a request is forwarded to the subject and not just
absorbed by the proxy silently, you can define a Proxy class that
doesn't understand any messages.
• Smalltalk lets you do this by defining Proxy as a class with no
superclass
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
3. Proxy doesn't always have to know the type of real
subject.
• If a Proxy class can deal with its subject solely through an abstract
interface, then there's no need to make a Proxy class for each
RealSubject class;
• the proxy can deal with all RealSubject classes uniformly.
• But if Proxies are going to instantiate RealSubjects (such as
in a virtual proxy), then they have to know t he concrete class.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Sample Code
1. A virtual proxy. The Graphic class defines the interface for
graphical objects:
The Image class implements the
Graphic interface to display image files.
Image overrides HandleMouse to let
users resize the image interactively.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
ImageProxy has the same interface as
Image:
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
The constructor saves a local copy of the name of the file
that stores the image, and it initializes -extent and -image:
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
2. Proxies that use doesNotUnderstand. You can make generic proxies
in Smalltalk by defining cl asses whose superclass is nil and defining the
doesNotUnderstand: method to handle messages.
The following method assumes the proxy has a real Subject method that returns
its real subject.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Known Uses
• The virtual proxy example from ET++ text building block
classes.
• NEXTSTEP: uses proxies (instances of class NXProxy)as local
representatives for objects that may be distributed.
Server creates proxies for remote objects when
clients request them.
On receiving a message, the proxy encodes it
along with its arguments and then forward s the
encoded message to the remote subject.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Related Patterns
1. Adapter ( 139) :
An adapter provides a different interface to the object it adapts. In
contrast,
a proxy provides the same interface as its subject.
a proxy used for access protection might refuse to perform an
operation that the subject will perform ,so its interface may be
effectively a subset of the subject's.
2. Decorator (175):
Although decorators can have similar implementations as
proxies,
decorators have a different purpose.
A decorator adds one or more responsibilities to an object,
whereas a
proxy controls access to an object.
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur
Most of the methods of LibraryServlet fall into one of five
categories:
1. One group contains methods that store information about the
user.
2. Methods to validate users and help assess access rights.
3. The getFile method reads an HTML file and returns its contents
as a String object.
4. The fourth group of methods are used for handling users who
may have invoked a command without actually logging in.
5. The final group of commands deal with processing the request
and responding to it. Refer page number 414
Department
Departmentof
of BLDEACETInstitute
BLDEACETInstituteofofTechnology
Technologyand
CSE
CSE and Vijayapur
Vijayapur