Understanding the Adapter Pattern in Software Design
Understanding the Adapter Pattern in Software Design
EL
PT
N
1
Intent: B A C Adapter Pattern
– Convert the interface of a class to the interface
expected by the users of the class.
– Allows classes to work together even when they have
EL
incompatible interfaces.
Also universal adapters?
Example (non-software):
PT
– You went to U.S.
– Had an Indian electrical appliance.
N
– How can you use it in U.S.?
– Use Adapters!
2
• A wrapper pattern Client Adapter Server
Adapter Pattern
• Problem: Convert the interface of a
class into one that a client expects.
– Lets classes work together --- that couldn’t otherwise --- because of incompatible interfaces
EL
– Used to provide a new interface to existing legacy components. New
package
• Two main adapter variants:
PT
– Class adapter:
• Uses interface implementation and inheritance mechanisms
– Object adapter:
N
• Uses delegation to adapt one interface to another
• Object adapters are much more common.
3
Essential Idea Behind Adapter Pattern
Client Target
Old
Target Adaptee
interface
Old New
Client package package
EL
Old New Adaptee
PT
interface interface
Adapter
Client Adapter New
N package
4
• Helps two incompatible types to communicate. Adapter
• When a client class expects an interface ---but that is Pattern
not supported by a server class,
• The adapter acts as a translator between the two types.
EL
Client
• 3 essential classes involved: Adapter Adaptee
PT
Client Target
o Adapter - class that wraps the operations of
the Adaptee in interfaces familiar to client. Adapter
N
o Adaptee - class with operations that the client
class desires to use. Adaptee
5
Recap:
Terminology
Target
EL
Adapter
PT
Adaptee
N
6
An adaptee may be given a new interface by an Class and
adapter in two ways: Object
•Inheritance Adapters
Adaptee
–Known as Class Adapter pattern
EL
Adapter
–The adapter is a sub-class of adaptee;
PT
•Delegation Adapter Adaptee
7
• There are many ways to implement a set Example 1 – Sets
• Assume:
– Your existing set implementation has poor performance.
• You got hold of a more efficient set class, Application Set
EL
– BUT: The new set has a different interface.
NewSet
PT
– Do not want to change voluminous client code
• Solution: Design a setAdapter class :
N
– Same interface as the existing set.. Adapter
8
Class Adapter: Main Idea
EL
Target Adaptee
Client
quack(); Cock-a-Doodle();
PT
NAdapter
quack();
9
Object Adapter: Main Idea
EL
Target Adaptee
Client
quack(); Cock-a-Doodle();
PT
NAdapter
quack();
10
Client OldSet Example:
add(Object e)
Problem
Existing del(Object e)
int cardinality()
contains(Object e)
EL
Got hold of Newset… Target
NewSet Want use this with client…
PT
insert(Object e)
remove(Object e)
int size() But, do not want
contains(Object e)
Adaptee
N to change Client
code…
11
Object Adapter --- main idea delegation Object
• Adapter internally holds an instance of the Adaptee Adapter
• Uses it to call Adaptee operations from within Pattern
operations supported by the Target.
EL
Target Adaptee
add() insert()
PT
Client
Adapter
add() N insert() ;
12
Client Code: Object
Adaptee a =new Adaptee(); Target t = new Adapter(a);
public void test() { [Link](); } Adapter -
Target Code: Adaptee Code: Code
interface Target { class Adaptee {
public void add(){} public void insert(){}
EL
} }
Adapter Code:
PT
class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee a) { adaptee = a;}
}
N
public void add() { [Link]();}
13
oAdapter makes <<interface>> Class
NewSet appear as OldSet
add(Object e)
NewSet Adaptation
OldSet to the client del(Object e) insert(Object e)
int cardinality() remove(Object e)
oOldSet is an contains(Object e) int size()
EL
interface, not a class contains(Object e)
PT
Adapter
Client
N
add(Object e)
del(Object e)
int cardinality()
contains(Object e)
insert(e) ;
14
Client Code:
Class Adapter
Target t = new SetAdapter(); - Code
public void test() { [Link](); }
EL
interface Target { class SetAdaptee {
public void add(){} public void insert(){}
} }
PT
Adapter Code:
class SetAdapter extends SetAdaptee implements Target{
}
N
public void request() { specificRequest();}
15
Adapter design pattern for comparing Objects
EL
StudComparator
PT
int compare()
N
Adapter pattern has been used in implementing the
“Comparable” interface in Java
16
Outline of StudentComparator
public class StudentComparator
implements Comparator<Student> {
EL
public int compare(Student s1, Student s2){
PT
return [Link]() – [Link]();}
} N
17
Solution: Object only ---Many subclasses to adapt: Variant:
• Too expensive to adapt each subclass. Universal
Adapter--Adapt
• Create single adapter to superclass interface.
Multiple
• Configure the AdaptedSet with the specific NewSet at Versions of
EL
run-time.
NewSet
Client OldSet
PT
adaptee
AdaptedSet NewSet
N
NewHashSet NewBitSet
18
public class IPhoneCharger {
public interface ChargeAdapter{
public void applePhoneCharge(){ Adapter
[Link]("The iPhone is charging ..."); } } public void phoneCharge(); }
EL
public class UniversalCharger implements ChargeAdapter{
IPhoneCharger iphoneCharger; iCharge1 iCharge2
PT
public UniversalCharger(IPhoneCharger iphoneCharger){
[Link] = iphoneCharger; }
public void phoneCharge() {
[Link](); }
N Object
adapter
19
Class Adapters: Consequences
• A concrete adapter created for a specific Adaptee (e.g.,
NewSet)
EL
PT
• + Can override Adaptee (e.g., NewSet) behavior:
N
– After all, Adapter is a subclass of Adaptee
20
• Single Adapter can handle many Object Adapters:
Adaptees (Universal adaptor): Consequences
– Can adapt the Adaptee class and all its
EL
subclasses.
• Hard to override Adaptee behavior
PT
– Because the Adapter uses but does not
N
inherit from Adaptee interface.
21
Other Issues
• How much adapting does adapter do?
– Simple forwarding of requests (renaming)?
EL
– Different set of operations and semantics?
PT
– At some point do the Adaptee and Adapter
interfaces and functionality diverge so much
N
that “adaption” is no longer the correct
term…
22
• Can help change behavior of Advantages
of Adapter
existing software: Pattern
– Without changing its source code.
EL
• Can help maintain legacy software:
PT
– Without making any modifications
N
to aging source code…
23
Bridge Pattern
EL
PT
N
24
• Also called Handle/Body pattern. Bridge
Pattern
– Split a complex class hierarchy into two hierarchies.
– One represents the abstraction (called the handle).
EL
– The other is the implementation,
PT
and is called the body.
N
– The handle forwards any invocations
to the body.
25
Conference
Participant
Motivation:
Example 1
EL
Special Tutorial Paper
Organiser Registrant
Guest Presenter Presenter
PT
Organiser
Student
Tutorial
Presenter
Industrial
N
Academic Student
Paper
Presenter
26
• In this case, multiple inheritance is not a particularly good solution Solution:
• Roles are a much better solution as they are more flexible
Roles
performs 1..* Conference
Conference
Member Role
EL
Special Tutorial Paper
PT
Organiser Registrant
Guest Presenter Presenter
Industrial
N Academic Student
27
• You designed a graphics package… Example 2
shape
EL
PT
Circle Line Rectangle
draw() draw() draw()
area(); area() area();
N
28
• Things worked fine until you had to support Example 2
mobile phones that can draw only low precision
shapes.
– You extended your design….
EL
shape
PT
Line Rectangle
LineLow
N
LineHigh RectLow RectHigh
29
• You soon had to support a different drawing primitive for
efficient display of transient views for animation…
– You extended your design again …. Example 2
shape
EL
PT
Line Rectangle
RectLow RectHigh
LineLow
N
LineHigh
30
•You soon needed a different way of drawing on Smartphones…
•Things were becoming pretty complicated … Bridge
until you decided to use bridge design pattern…
defines the interface
shapes to draw
Design
Pattern
Shape
EL
Drawer
PT
Line TriangleN Hi Res Low Res
31
Bridge
Shape Design
Drawer
Pattern
EL
PT
Line Triangle Hi Res Low Res
N
32
Separate the
abstraction
from
Shape Drawer implementation
defines the interface
shapes to draw
EL
Abstraction Implementation
PT
Line Triangle Hi Res Low Res
N
Bridge Design Pattern
33
Why the Name
Shape Drawer Bridge?
Provides A
Bridge Between
the Application
EL
and Solution
domains…
Line Triangle Hi Res Low Res
PT
Application Domain
N Solution Domain
Terms Terms
34
<<abstract>> <<interface>> Bridge:
Structure
Abstraction Implementation
+ Operation() + Implementation()
EL
Client RefinedAbstraction1
+ Operation()
PT
RefinedAbstraction2
ConcreteImplementA ConcreteImplementB
+ Operation()
N
+ConcreteImplementA() +ConcreteImplementB()
35
Participants
• Abstraction
• RefinedAbstraction
EL
• Implementor
PT
N
• ConcreteImplementers
36
Participants contd…
•Abstraction
– Defines the abstract interface
EL
– Maintains a reference to the implementer
PT
•RefinedAbstraction
N
– Extends the interface defined by
Abstraction
37
Participants contd…
•Implementer
– Defines the interface for the
implementation classes
EL
PT
•ConcreteImplementer
N
– Implements the implementer interface
38
Collaborators
• Abstraction forwards client
requests to Implementer object.
EL
– Clients interface with abstraction class.
PT
– Abstraction class forward any requests
N
to the implementer class.
39
Example 1
Window Window
EL
MSWindow MacWindow MSWindow MacWindow IconWindow
PT
N MSIWindow MacIWindow
40
bridge
Window WindowImp
Example 1:
drawText() devDrawText()
Solution
drawRect() devDrawRect()
EL
PT
IconWindow
drawBorder()
N
ApplicationWindow
drawCloseBox()
MSWindowImp
devDrawText()
devDrawLine()
MacWindowImp
devDrawText()
devDrawLine()
41
Consider thread scheduling : Example 2
Thread
Scheduler
EL
Preemptive Thread Time sliced Thread
Scheduler Scheduler
PT
Unix PTS Windows Unix TSTS Windows
PTS
N
A class for each permutation of dimensions!
TSTS
42
We need to add support for Java platform also… Example 1
Thread Scheduler
EL
Preemptive Thread Time sliced Thread
Scheduler Scheduler
PT
Unix PTS Windows PTS Unix TSTS Windows TSTS
43
• Refactoring into two orthogonal hierarchies: Example 4: Solution
–One for platform-dependent abstractions a
nd other for platform independent implementations
EL
Thread ThreadSched-
Scheduler Impl
PT
Preemptive Time sliced Unix Windows
Thread
Scheduler
Thread
N
Scheduler
JVM
44
• Suppose an abstraction has several implementations:
– Inheritance is commonly used to accommodate these!!!
1. Inheritance binds an implementation to Observation
EL
the abstraction permanently:
– It becomes difficult to modify and reuse abstraction and
PT
implementations independently.
2. Inheritance without a Bridge:
N
– Leads to violation of single responsibility principle (SRP)
45
Overuse of inheritance.
“As a beginning object-oriented analyst, I had a tendency to
solve the kind of problem I have seen here by using
EL
special cases, taking advantage of inheritance. I loved the
idea of inheritance because it seemed new and powerful.
PT
I used it whenever I could. This seems to be normal for
N
many beginning analysts, but it is naive: given this new
“hammer,” everything seems like a nail. “
46
Use bridge Pattern when: Bridge: Applicability
• You want to avoid a permanent binding between an
abstraction and its implementation.
EL
– Implementation may be selected or switched at run
time.
PT
• Both the abstraction and their implementation should be
extensible by subclassing without impacting the clients:
N
– Even code should not be recompiled.
47
• Circle Shape problem Bridge Pattern: Example 3
– Different implementations for drawing circle
– A method for changing the circle abstractly
• Participants <<abstract>>
Abstraction
<<interface>>
Implementor
– Abstraction
EL
+ Operation() + Implementation()
• Interface Shape
– RefinedAbstraction
PT
• Class CircleShape
– Implementation
• Interface DrawingAPI RefinedAbstraction
– ConcreteImplementations
• Class DrawingAPI1
N + Operation() ConcreteImplementA
+ Implementation()
ConcreteImplementB
+ Implementation()
• Class DrawingAPI2
48
Interface DrawingImplementation{ Bridge Pattern
public void drawCircle(double x, double y, Example 3
double radius);
}
EL
<<abstract>> <<interface>>
Abstraction DrawingImplementation
PT
+ Operation() + Implementation()
RefinedAbstraction
+ Operation()
N
ConcreteImplementorA ConcreteImplementorB
+ Implementation() + Implementation()
49
class ConcreteImplementerA implements DrawingImplementer{ Bridge
public void drawCircle(double x, double y, double radius) { Pattern
[Link]("[Link] at %f:%f radius %f\n", x, y, radius);
Example 3
<<abstract>> <<interface>>
} Abstraction DrawingImplementer
EL
+ Operation() + Implementation()
PT
RefinedAbstraction
N
public void drawCircle(double x, double y, double radius){
}
50
interface Shape { Bridge
public void draw(); Pattern:
public void resizeByPercentage(double pct);
Example 3
}
EL
<<abstract>> <<interface>>
Shape DrawingImplementor
+ Operation() + Implementation()
PT
RefinedAbstraction
+ Operation()
N
ConcreteImplementorA ConcreteImplementorB
+ Implementation() + Implementation()
51
class CircleShape implements Shape { /** "Refined Abstraction" */ Bridge Pattern
private double x, y, radius;
private DrawingAPI drawingAPI; Example 3
public CircleShape(double x, double y, double radius, DrawingAPI
drawingAPI)
{ this.x = x; this.y = y; [Link] = radius; [Link] = drawingAPI;
}
EL
// low-level i.e. Implementation specific <<abstract>> <<interface>>
Shape DrawingImplementor
public void draw() { + Operation()
+ Implementation()
[Link](x, y, radius);
PT
}
// high-level i.e. Abstraction specific
public void resizeByPercentage(double pct) { CircleShape
}
radius *= pct;
}
N + Operation() ConcreteImplementorA
+ Implementation()
ConcreteImplementorB
+ Implementation()
52
/** "Client" */
class BridgePattern {
Bridge Pattern Example 3
public static void main(String[] args) {
Shape[] shapes = new Shape[] {
new CircleShape(1, 2, 3, new DrawingAPI1()), new CircleShape(5, 7,
EL
11, new DrawingAPI2()) }
for (Shape shape : shapes) {
[Link](2.5);
PT
[Link]();
}
}
}
N
53
Example 4
imp
Database ODBC
Application Implementation
EL
PT
DB2 ODBC Oracle ODBC Informix ODBC
Driver N Driver Driver
54
Bridge Pattern: Exercise 1
• How do we simplify the following design?
Car
EL
PT
Ford Toyota Sporty Truck SUV
SportyFord ToyotaTruck
NFordTruck SportyToyota FordSUV
55
Exercise 1: Solution…
Use Bridge when you might otherwise be tempted
to use multiple inheritance...
Car CarManufacturer
EL
PT
Sporty Truck N Ford Toyota
56
When should we apply Bridge Pattern?
• We want run-time binding of implementation.
• We need to overcome a proliferation of classes:
EL
–Resulted from a coupled interface and numerous
PT
implementations
N
–We need to map these into orthogonal class
hierarchies
57
Implementation Issues
• How and when to decide which implementer to instantiate?
• Depends:
– if Abstraction knows about a concrete implementer, then it can
EL
instantiate it.
PT
– Or it can delegate the decision to another object (to an abstract
factory for example)
N
• “Find what varies and encapsulate it” and “favor
object composition over class inheritance”
58
Benefits
• Decoupling abstraction from implementation
• Reduction in number of sub-classes
• Reduced complexity and reduction in executable size
EL
• Interface and Implementation can be varied
PT
independently
• Improved extensibility:
N
– Abstraction and Implementation can be extended
independently
59
Drawbacks?
•Increased Complexity???
EL
•Double Indirection :
PT
–Abstraction Implementation
N
ConcreteImplementation
60
Proxy Pattern
EL
PT
N
61
• Problem: How should a client invoke the Proxy
services of a server when access to the server (Surrogate)
should be managed in some way? Pattern
• Solution: A proxy object should be created at the
client side.
EL
c P cP
• Proxy Role: The proxy can help to c P S
PT
– Authenticate cP P
c
– Hide details of network operations.
N
• Determine server address,
• Communicate with the server, obtain server response and
seamlessly pass that to the client, etc.
62
Digression: Network Proxy Server
• What is the role of a network proxy server?
– To keep machines behind it
anonymous, mainly for security.
EL
– To speed up access to resources using caching.
– To prevent downloading the same content multiple
PT
times and save bandwidth (caching).
– To log usage to support reporting of company
N
employee-wise Internet usage.
– Firewall: Scan for malware
63
• Encryption / SSL acceleration: Secure Sockets Layer (SSL)
encryption is usually not done by the web browser itself,
but by the proxy that is equipped with SSL acceleration
hardware.
• Load balancing: can distribute the load to several web
EL
servers, each web server serving its own application area.
• Compression: proxy server can optimize and compress
PT
the content to speed up the load time.
• Spoon feeding: Address the problem caused by slow
N
clients by caching the response from the web servers and
slowly "spoon feeding" it to the client.
64
Proxy: Some Insights
• Use Proxy pattern whenever the services provided
by a supplier need to be managed in some way
without disturbing the supplier interface.
EL
• Example: You require some additional conditions to
PT
be satisfied before the actual object is accessed:
N
• Consider loading an image from disk only when it is
actually needed.
65
Proxy Pattern
• Proxy object has the same interface as the target object:
– Proxy stores a reference to the target object
EL
– Forwards (delegates) requests to it.
• Sometimes more sophistication needed than
PT
just a simple reference to an object:
N
– That is, we want to wrap code around
references to an object…
66
• A Structural Pattern: Proxy Pattern
–Provides surrogate for some object, Client Object
EL
• Real target may not always be instantiated
PT
immediately:
N
–Due to performance, location, or access
restrictions.
67
Proxy Usage 1: Help Reduce Expensive Steps
• Example of what is expensive…
– Heavy weight object Creation
– Object Initialization
EL
• Defer object creation and initialization to the time the
object is actually need.
PT
• Proxy pattern:
– Reduces the cost of accessing objects
N
– The proxy object acts as a stand-in for the real object
– The proxy creates the real object only if the user asks for it
68
• Create a Proxy object that implements the Proxy Solution
same interface as the real object… <<interface>>
Subject
Client
• The Proxy object contains a reference to
request()
...
EL
• Clients have a reference to the Proxy: RealSubject
request()
delegate Proxy
request()
... ...
– Not the real object
PT
• Client invokes operations only on the Proxy:
Client
N
– Proxy may perform additional processing before delegating…
Proxy Real Object
Class Diagram Proxy Structure
<<abstract>>
Subject
Client request() request() {
... ...
[Link]()
...
EL
}
PT
RealSubject Proxy
delegate
request()
... N request()
...
70
Proxy Pattern
• Three Classes: Subject, RealSubject, and Proxy.
<<interface>>
• Interface Subject:
Subject
Client request()
...
EL
–Implemented both by RealSubject, and Proxy.
• Proxy: RealSubject
delegate
Proxy
PT
request() request()
... ...
71
Subject
<<interface>>
f();
p();
g();
EL
Proxy
PT
RealSubject
f(); f();
delegate
p();
g(); N p();
g();
72
interface Subject { void f(); void g(); void h();} Proxy
class Proxy implements Subject { Code
private Subject implementation;
public Proxy() { implementation = new RealSubject(); }
public void f() {implementation.f();}
public void g() {implementation.g();}
class Client{
EL
public void h() {implementation.h();}
Proxy p = new Proxy();
}
p.f(); p.g(); p.h(); }
PT
class RealSubject implements Subject {
public void f() {[Link]("Implementation.f()");}
public void g() {[Link]("Implementation.g()");}
}
N
public void h() {[Link]("Implementation.h()");}
73
:Client :Proxy :RealSubject Sequence
Diagram
for Proxy
expensiveMethod()
EL
( if needed )
realExpensiveMethod()
PT
N
Proxy forwards requests to RealSubject when necessary.
74
• Virtual proxy: Many Kinds of Proxies…
– Delays creation or loading of large or computationally
expensive objects (lazy construction)
– Proxy is a standin --- postpones accessing the real subject.
EL
• Remote proxy: Client Object
PT
address space)
– Hides the fact that an object is not local
N
- Encode and send the request to the real subject in a
different address space.
75
• Synchronization Proxy
– Controls access to a target object when multiple objects
Kinds of
access it. Proxies
• Cache Proxy
– Hold results temporarily
EL
– Saves data for clients to share so data is only fetched or
calculated once
PT
– Caching of information: Helpful if information does not
change too often.
• Copy-on-write: N
– Postpones creation of a copy of an object until it is really
necessary.
76
• Protection Proxy Kinds of
– Checks access permission to the real object when it is Proxies
accessed.
– Ensures that only authorized clients access a supplier
EL
in legitimate ways
– Useful when different objects should have different
PT
access and viewing rights for the same document.
– Example: Grade information shared by administrators,
N
teachers and students.
77
Proxy
Client «interface»
Pattern
Subject
EL
PT
Proxy delegate
RealSubject
N
78
Virtual Proxy: Why Stand-in?
1. The image is expensive to load
2. The complete image is not always necessary
EL
PT
lightweight
2MB
N 2KB 79
79
Virtual Proxy Motivation: Image Viewer
aTextDocument
image
EL
anImageProxy
fileName
anImage
PT
data
in memory
N on disk
80
Virtual Proxy example Image
boundingBox()
draw()
• Images are stored and loaded separately
from text
ProxyImage RealImage
realSubject
EL
boundingBox() boundingBox()
draw() draw()
PT
displays a grey rectangle in place of the image
N
• The client cannot tell whether it is dealing
with a ProxyImage instead of a RealImage
81
Example Application: Picture Viewer
• A picture viewer is to be developed that can should handle
displaying many high quality images.
• Requirement: Opening the viewer should be fast:
EL
–Becomes slow if all images must be first loaded.
PT
• No need to load all at the start:
–All pictures not viewable in the display Window.
N
• Create images on demand !
83
N
PT
84 EL
Proxy Pattern
Client
«interface»
Image Example 1
public interface Image {
public void displayImage();
}
EL
PT
ProxyImage delegate
RealImage
N
85
• Word Processor: Similar Uses:
Lazy Loading
– Suppose a text document contains lots of
multimedia objects and yet should load fast
EL
– Create proxies that represent large images,
movies, etc. --- only load objects on
PT
demand as they become visible on the
N
screen (only a small part of the document is
visible at a time)
86
• Rather than instantiating an expensive Lazy
object right away: Loading
– Create a proxy instead, and give the proxy to
the client
EL
• The proxy creates the object on demand
PT
when the client first uses it
– If the client never uses the object, the
N
expense of creating it is never incurred…
87
• A hybrid approach can be used:
Lazy
Loading
– The proxy implements some operations itself.
– Create the real object only if the client invokes
EL
one of the operations it cannot perform
PT
• A proxy stores necessary information to
create the object on-the-fly:
N
– file name, network address, etc.
88
Graphic
Draw() Image Proxy:
Document Editor GetExtent()
Store()
Code Example
Load()
EL
imageImp fileName image=LoadImage(fileName);
extent extent [Link]();
Draw() Draw()
GetExtent()
PT
GetExtent()
Store() Store()
Load() Load() if(image= =0)
return(extent);
else
N return([Link]();
89
interface Graphic {
Image Proxy:
public void displayImage(); Code Example
public void loadImage();
}
class Image implements Graphic {
EL
private String filename;
public Image(String filename) {
PT
[Link] = filename;
[Link]("Loading "+filename);
}
N
public void displayImage() {
[Link]("Displaying "+filename); }
}
90
public class ImageProxy implements Graphic { Proxy
private String filename;
private Image image;
Pattern
Example 1
public ImageProxy (String filename){ delegate request
[Link] = filename; to real subject
EL
}
public void displayImage() {
if (image == null) {
PT
image = new RealImage(filename); //load only on demand
}
}
N
[Link]();
91
public class ProxyExample {
public static void main(String[] args) { Proxy
Example -
ArrayList<Image> images = new ArrayList<Image>(); -- Client
[Link](new ProxyImage("HiRes_10MB_Photo1"));
[Link](new ProxyImage("HiRes_10MB_Photo2"));
EL
[Link](new ProxyImage("HiRes_10MB_Photo3"));
PT
[Link](0).displayImage();
[Link](1).displayImage();
}
N
[Link](0).loadImage();
92
• The proxy object: Remote Proxy
– Assembles data into a network message
– Sends it to the remote object (Server)
EL
• A remote receiver: Inter
PT
Client Proxy
net Server
93
• Stand-in for an object often needed because it is:
– Not locally available; Remote Proxy
– Instantiation and access are complex
– Needs protected access for security.
EL
Inter
• The stand-in must: Client Proxy
net Server
PT
– Have the same interface as the real object;
– Handle as many messages as it can;
N
– Delegate messages to the real object when necessary.
94
Remote
<<interface>> Proxy
Pattern
Supplier Structure
EL
request()
PT
Client
N
ProxySupplier RealSupplier
95
Proxy Pattern
sd ProxyBehavior Behavior
EL
request()
PT
request() request0()
request()
N
96
• Read-only Collections Uses in Java
– Wrap a collection object in a proxy that only allows read-only operations to be
invoked on the collection
Collection
– All other operations throw exceptions
– List unmodifiableList=[Link](List list);
EL
• Returns read-only List proxy
• Synchronized Collections
PT
– Wrap collection object in a proxy that ensures only one thread at a time is
allowed to access the collection
– Proxy acquires lock before calling a method, and releases lock after the method
completes
N
– List [Link](List list);
• Returns a synchronized List proxy
97
Other Proxy Uses: Copy-on-Write
• Multiple clients share the same object:
– as long as nobody tries to change it
• When a client attempts to change the object:
EL
– They get their own private copy of the object
• Read-only clients continue to share the original object:
PT
– while writers get their own copies
N
• Maximize resource sharing, while making it look like
everyone has own object.
98
• Highly optimized String classes often use this Uses:
approach Copy-on-
Write
• To make this work:
EL
–Clients are given proxies rather than direct references
to the object
PT
• When a write operation occurs:
–A proxy makes a private copy of the object on-the-
N
fly to insulate other clients from the changes
99
Before any Write
Client A Proxy A Decorator
Known Uses:
Client B Proxy B Real Subject
Copy-on-Write
Client C Proxy C
EL
PT
Client A Proxy A After Write by C
Client B
Client C
N
Proxy B
Proxy C
Real Subject
100
Client A Proxy A
Uses:
Reference
Client B Proxy B : Real Subject
RefCount : int Counting
Client C Proxy C
EL
• Proxies maintain the reference count inside the
object
PT
• The last proxy to go away is responsible for
deleting the object:
N
– That is, when the reference count goes to 0, delete the
object.
Proxy: Final Analysis
EL
– A Proxy introduces a level of indirection.
PT
not change the object’s interface.
N
102
Proxy: Related Patterns
• Adapter:
– Provides a different interface to an object,
EL
• Decorator:
PT
– Similar structure as proxy, but different purpose.
N
– Decorator adds responsibilities whereas proxy
controls access.
103