SlideShare una empresa de Scribd logo
1 de 18
The Proxy PatternThe Proxy Pattern
Code Review: 7/19/13 Chester Hartin
ProblemsProblems
 You need to control access to an objectYou need to control access to an object
 Defer the cost of object creation andDefer the cost of object creation and
initialization until actually usedinitialization until actually used
SolutionSolution
 Create a Proxy object that implements theCreate a Proxy object that implements the
same interface as the real objectsame interface as the real object
 The Proxy object contains a reference to theThe Proxy object contains a reference to the
real objectreal object
 Clients are given a reference to the Proxy, notClients are given a reference to the Proxy, not
the real objectthe real object
 All client operations on the object pass throughAll client operations on the object pass through
the Proxy, allowing the Proxy to performthe Proxy, allowing the Proxy to perform
additional processingadditional processing
Proxy PatternProxy Pattern
 Acts as an intermediary between the client and the targetActs as an intermediary between the client and the target
objectobject
 Why? Target may be inaccessible (network issues, too large toWhy? Target may be inaccessible (network issues, too large to
run, resources…)run, resources…)
 Has the same interface as the target objectHas the same interface as the target object
 The proxy has a reference to the target object and forwardsThe proxy has a reference to the target object and forwards
(delegates) requests to it(delegates) requests to it
 Useful when more sophistication is needed than a simpleUseful when more sophistication is needed than a simple
reference to an object (i.e. we want to wrap code aroundreference to an object (i.e. we want to wrap code around
references to an object)references to an object)
 Proxies are invisible to the client, so introducing proxiesProxies are invisible to the client, so introducing proxies
does not affect client codedoes not affect client code
Proxy patternProxy pattern
 Interface inheritance is used to specify the interfaceInterface inheritance is used to specify the interface
shared byshared by ProxyProxy andand RealSubject.RealSubject.
 Delegation is used to catch and forward any accesses toDelegation is used to catch and forward any accesses to
thethe RealSubjectRealSubject (if desired)(if desired)
 Proxy patterns can be used for lazy evaluation and forProxy patterns can be used for lazy evaluation and for
remote invocation.remote invocation.
Subject
Request()
RealSubject
Request()
Proxy
Request()
realSubject
6
Proxy PatternProxy Pattern
 Types of ProxiesTypes of Proxies
 Virtual Proxy / Cache ProxyVirtual Proxy / Cache Proxy: Create an: Create an
expensive object on demand (lazyexpensive object on demand (lazy
construction) / Hold results temporarilyconstruction) / Hold results temporarily
 Remote ProxyRemote Proxy: Use a local representative for: Use a local representative for
a remote object (different address space)a remote object (different address space)
 Protection ProxyProtection Proxy: Control access to shared: Control access to shared
objectobject
Virtual Proxy ExamplesVirtual Proxy Examples
 Object-Oriented DatabasesObject-Oriented Databases
 Objects contain references to each otherObjects contain references to each other
 Only load the real object from disk if a method is neededOnly load the real object from disk if a method is needed
 Resource ConservationResource Conservation
 Save memory by only loading objects that are actually usedSave memory by only loading objects that are actually used
 Objects that are used can be unloaded after awhile, freeing upObjects that are used can be unloaded after awhile, freeing up
memory (Can also be Cached Proxy)memory (Can also be Cached Proxy)
 Word ProcessorWord Processor
 Documents that contain lots of multimedia objects should still loadDocuments that contain lots of multimedia objects should still load
fastfast
 Create proxies that represent large images, movies, etc., and onlyCreate proxies that represent large images, movies, etc., and only
load objects on demand as they become visible on the screenload objects on demand as they become visible on the screen
Image Proxy (1 or 3)Image Proxy (1 or 3)
interface Image {
public void displayImage();
}
class RealImage implements Image {
private String filename;
public RealImage(String filename) {
this.filename = filename;
System.out.println("Loading "+filename);
}
public void displayImage() { System.out.println("Displaying "+filename); }
}
Image Proxy (2 of 3)Image Proxy (2 of 3)
class ProxyImage implements Image {
private String filename;
private RealImage image = null;
public ProxyImage(String filename) { this.filename = filename; }
public void displayImage() {
if (image == null) {
image = new RealImage(filename); // load only on demand
}
image.displayImage();
}
}
Image Proxy (3 of 3)Image Proxy (3 of 3)
class ProxyExample {
public static void main(String[] args) {
ArrayList<Image> images = new ArrayList<Image>();
images.add( new ProxyImage("HiRes_10GB_Photo1") );
images.add( new ProxyImage("HiRes_10GB_Photo2") );
images.add( new ProxyImage("HiRes_10GB_Photo3") );
images.get(0).displayImage(); // loading necessary
images.get(1).displayImage(); // loading necessary
images.get(0).displayImage(); // no loading necessary; already done
// the third image will never be loaded - time saved!
}
}
Main
DisplayImage()
RealImage
DisplayImage()
ProxyImage
DisplayImage()
realSubject
Image Proxy DiagramImage Proxy Diagram
12
Sample Context: Word ProcessorSample Context: Word Processor
Paragraph
Document
Paragraph
Image
Document
Draw()
GetExtent()
Store()
Load()
Glyph
Text
extent
Draw()
GetExtent()
Store()
Load()
Paragraph
fileName
extent
Draw()
GetExtent()
Store()
Load()
Image
content
extent
Draw()
GetExtent()
Store()
Load()
Table
13
ForcesForces
1. The image is expensive to load1. The image is expensive to load
2. The complete image is not always2. The complete image is not always
necessarynecessary
2MB 2KB
optimize!
Simple DiagramSimple Diagram
image
aTextDocument
fileName
animageProxy
data
animage
inmemory ondisc
Implementation DiagramImplementation Diagram
DocumentEditor
Draw()
GetExtent()
Store()
Load()
Graphic*
imageImp
extent
Draw()
GetExtent()
Store()
Load()
Image
fileName
extent
Draw()
GetExtent()
Store()
Load()
ImageProxy if (image==0){
image=LoadImage(fileName);
}
image->Draw()
if (image==0){
returnextent;
}else{
returnimage->GetExtent();
}
image
Remote ProxyRemote Proxy
 The Client and Real Subject are in different processesThe Client and Real Subject are in different processes
or on different machines, and so a direct method callor on different machines, and so a direct method call
will not workwill not work
 The Proxy's job is to pass the method call acrossThe Proxy's job is to pass the method call across
process or machine boundaries, and return the resultprocess or machine boundaries, and return the result
to the client (with Broker's help)to the client (with Broker's help)
Protection ProxyProtection Proxy
 Different clients have different levels of accessDifferent clients have different levels of access
privileges to an objectprivileges to an object
 Clients access the object through a proxyClients access the object through a proxy
 The proxy either allows or rejects a method callThe proxy either allows or rejects a method call
depending on what method is being called anddepending on what method is being called and
who is calling it (i.e., the client's identity)who is calling it (i.e., the client's identity)
Additional UsesAdditional Uses
 Read-only CollectionsRead-only Collections
 Wrap collection object in a proxy that only allows read-onlyWrap collection object in a proxy that only allows read-only
operations to be invoked on the collectionoperations to be invoked on the collection
 All other operations throw exceptionsAll other operations throw exceptions
 List Collections.unmodifiableList(List list);List Collections.unmodifiableList(List list);
 Returns read-only List proxyReturns read-only List proxy
 Synchronized CollectionsSynchronized Collections
 Wrap collection object in a proxy that ensures only one thread atWrap collection object in a proxy that ensures only one thread at
a time is allowed to access the collectiona time is allowed to access the collection
 Proxy acquires lock before calling a method, and releases lockProxy acquires lock before calling a method, and releases lock
after the method completesafter the method completes
 List Collections.synchronizedList(List list);List Collections.synchronizedList(List list);
 Returns a synchronized List proxyReturns a synchronized List proxy

Más contenido relacionado

La actualidad más candente

Creational pattern
Creational patternCreational pattern
Creational patternHimanshu
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patternsThaichor Seng
 
OOAD unit1 introduction to object orientation
 OOAD unit1 introduction to object orientation OOAD unit1 introduction to object orientation
OOAD unit1 introduction to object orientationDr Chetan Shelke
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design PatternsAnton Keks
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design PatternAdeel Riaz
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 
MVC Architecture
MVC ArchitectureMVC Architecture
MVC ArchitecturePrem Sanil
 
Introduction to Struts 1.3
Introduction to Struts 1.3Introduction to Struts 1.3
Introduction to Struts 1.3Ilio Catallo
 
PATTERNS03 - Behavioural Design Patterns
PATTERNS03 - Behavioural Design PatternsPATTERNS03 - Behavioural Design Patterns
PATTERNS03 - Behavioural Design PatternsMichael Heron
 
Clean Architecture Applications in Python
Clean Architecture Applications in PythonClean Architecture Applications in Python
Clean Architecture Applications in PythonSubhash Bhushan
 

La actualidad más candente (20)

Creational pattern
Creational patternCreational pattern
Creational pattern
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
 
Use Case Modeling
Use Case ModelingUse Case Modeling
Use Case Modeling
 
Prototype Design Pattern
Prototype Design PatternPrototype Design Pattern
Prototype Design Pattern
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patterns
 
Patron de diseño proxy
Patron de diseño proxyPatron de diseño proxy
Patron de diseño proxy
 
OOAD unit1 introduction to object orientation
 OOAD unit1 introduction to object orientation OOAD unit1 introduction to object orientation
OOAD unit1 introduction to object orientation
 
Js: master prototypes
Js: master prototypesJs: master prototypes
Js: master prototypes
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Struts
StrutsStruts
Struts
 
Composite pattern
Composite patternComposite pattern
Composite pattern
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Java Beans
Java BeansJava Beans
Java Beans
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
MVC Architecture
MVC ArchitectureMVC Architecture
MVC Architecture
 
Mediator pattern
Mediator patternMediator pattern
Mediator pattern
 
JNDI
JNDIJNDI
JNDI
 
Introduction to Struts 1.3
Introduction to Struts 1.3Introduction to Struts 1.3
Introduction to Struts 1.3
 
PATTERNS03 - Behavioural Design Patterns
PATTERNS03 - Behavioural Design PatternsPATTERNS03 - Behavioural Design Patterns
PATTERNS03 - Behavioural Design Patterns
 
Clean Architecture Applications in Python
Clean Architecture Applications in PythonClean Architecture Applications in Python
Clean Architecture Applications in Python
 

Similar a Proxy pattern

Gang of four Proxy Design Pattern
 Gang of four Proxy Design Pattern Gang of four Proxy Design Pattern
Gang of four Proxy Design PatternMainak Goswami
 
INTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMINGINTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMINGProf Ansari
 
Cross-Platform Native Mobile Development with Eclipse
Cross-Platform Native Mobile Development with EclipseCross-Platform Native Mobile Development with Eclipse
Cross-Platform Native Mobile Development with EclipsePeter Friese
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805LearningTech
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805LearningTech
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method InvocationSabiha M
 
Developing your first application using FI-WARE
Developing your first application using FI-WAREDeveloping your first application using FI-WARE
Developing your first application using FI-WAREFermin Galan
 
Dojo - from web page to web apps
Dojo - from web page to web appsDojo - from web page to web apps
Dojo - from web page to web appsyoavrubin
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorialKat Roque
 
Distributed System by Pratik Tambekar
Distributed System by Pratik TambekarDistributed System by Pratik Tambekar
Distributed System by Pratik TambekarPratik Tambekar
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWAREFIWARE
 
Secure Mashups
Secure MashupsSecure Mashups
Secure Mashupskriszyp
 
Introduction To Dojo
Introduction To DojoIntroduction To Dojo
Introduction To Dojoyoavrubin
 
Application Frameworks: The new kids on the block
Application Frameworks: The new kids on the blockApplication Frameworks: The new kids on the block
Application Frameworks: The new kids on the blockRichard Lord
 

Similar a Proxy pattern (20)

Gang of four Proxy Design Pattern
 Gang of four Proxy Design Pattern Gang of four Proxy Design Pattern
Gang of four Proxy Design Pattern
 
INTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMINGINTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMING
 
Cross-Platform Native Mobile Development with Eclipse
Cross-Platform Native Mobile Development with EclipseCross-Platform Native Mobile Development with Eclipse
Cross-Platform Native Mobile Development with Eclipse
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocation
 
RMI (Remote Method Invocation)
RMI (Remote Method Invocation)RMI (Remote Method Invocation)
RMI (Remote Method Invocation)
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 
Developing your first application using FI-WARE
Developing your first application using FI-WAREDeveloping your first application using FI-WARE
Developing your first application using FI-WARE
 
Dojo - from web page to web apps
Dojo - from web page to web appsDojo - from web page to web apps
Dojo - from web page to web apps
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorial
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
Distributed System by Pratik Tambekar
Distributed System by Pratik TambekarDistributed System by Pratik Tambekar
Distributed System by Pratik Tambekar
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Volley in android
Volley in androidVolley in android
Volley in android
 
Secure Mashups
Secure MashupsSecure Mashups
Secure Mashups
 
Introduction To Dojo
Introduction To DojoIntroduction To Dojo
Introduction To Dojo
 
Application Frameworks: The new kids on the block
Application Frameworks: The new kids on the blockApplication Frameworks: The new kids on the block
Application Frameworks: The new kids on the block
 

Más de Chester Hartin

Más de Chester Hartin (8)

Xamarin 101
Xamarin 101Xamarin 101
Xamarin 101
 
Asynchronous programming
Asynchronous programmingAsynchronous programming
Asynchronous programming
 
Elapsed time
Elapsed timeElapsed time
Elapsed time
 
Dependency injection
Dependency injectionDependency injection
Dependency injection
 
Map kit
Map kitMap kit
Map kit
 
Hash tables
Hash tablesHash tables
Hash tables
 
Parallel extensions
Parallel extensionsParallel extensions
Parallel extensions
 
Reflection
ReflectionReflection
Reflection
 

Último

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 

Último (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

Proxy pattern

  • 1. The Proxy PatternThe Proxy Pattern Code Review: 7/19/13 Chester Hartin
  • 2. ProblemsProblems  You need to control access to an objectYou need to control access to an object  Defer the cost of object creation andDefer the cost of object creation and initialization until actually usedinitialization until actually used
  • 3. SolutionSolution  Create a Proxy object that implements theCreate a Proxy object that implements the same interface as the real objectsame interface as the real object  The Proxy object contains a reference to theThe Proxy object contains a reference to the real objectreal object  Clients are given a reference to the Proxy, notClients are given a reference to the Proxy, not the real objectthe real object  All client operations on the object pass throughAll client operations on the object pass through the Proxy, allowing the Proxy to performthe Proxy, allowing the Proxy to perform additional processingadditional processing
  • 4. Proxy PatternProxy Pattern  Acts as an intermediary between the client and the targetActs as an intermediary between the client and the target objectobject  Why? Target may be inaccessible (network issues, too large toWhy? Target may be inaccessible (network issues, too large to run, resources…)run, resources…)  Has the same interface as the target objectHas the same interface as the target object  The proxy has a reference to the target object and forwardsThe proxy has a reference to the target object and forwards (delegates) requests to it(delegates) requests to it  Useful when more sophistication is needed than a simpleUseful when more sophistication is needed than a simple reference to an object (i.e. we want to wrap code aroundreference to an object (i.e. we want to wrap code around references to an object)references to an object)  Proxies are invisible to the client, so introducing proxiesProxies are invisible to the client, so introducing proxies does not affect client codedoes not affect client code
  • 5. Proxy patternProxy pattern  Interface inheritance is used to specify the interfaceInterface inheritance is used to specify the interface shared byshared by ProxyProxy andand RealSubject.RealSubject.  Delegation is used to catch and forward any accesses toDelegation is used to catch and forward any accesses to thethe RealSubjectRealSubject (if desired)(if desired)  Proxy patterns can be used for lazy evaluation and forProxy patterns can be used for lazy evaluation and for remote invocation.remote invocation. Subject Request() RealSubject Request() Proxy Request() realSubject
  • 6. 6 Proxy PatternProxy Pattern  Types of ProxiesTypes of Proxies  Virtual Proxy / Cache ProxyVirtual Proxy / Cache Proxy: Create an: Create an expensive object on demand (lazyexpensive object on demand (lazy construction) / Hold results temporarilyconstruction) / Hold results temporarily  Remote ProxyRemote Proxy: Use a local representative for: Use a local representative for a remote object (different address space)a remote object (different address space)  Protection ProxyProtection Proxy: Control access to shared: Control access to shared objectobject
  • 7. Virtual Proxy ExamplesVirtual Proxy Examples  Object-Oriented DatabasesObject-Oriented Databases  Objects contain references to each otherObjects contain references to each other  Only load the real object from disk if a method is neededOnly load the real object from disk if a method is needed  Resource ConservationResource Conservation  Save memory by only loading objects that are actually usedSave memory by only loading objects that are actually used  Objects that are used can be unloaded after awhile, freeing upObjects that are used can be unloaded after awhile, freeing up memory (Can also be Cached Proxy)memory (Can also be Cached Proxy)  Word ProcessorWord Processor  Documents that contain lots of multimedia objects should still loadDocuments that contain lots of multimedia objects should still load fastfast  Create proxies that represent large images, movies, etc., and onlyCreate proxies that represent large images, movies, etc., and only load objects on demand as they become visible on the screenload objects on demand as they become visible on the screen
  • 8. Image Proxy (1 or 3)Image Proxy (1 or 3) interface Image { public void displayImage(); } class RealImage implements Image { private String filename; public RealImage(String filename) { this.filename = filename; System.out.println("Loading "+filename); } public void displayImage() { System.out.println("Displaying "+filename); } }
  • 9. Image Proxy (2 of 3)Image Proxy (2 of 3) class ProxyImage implements Image { private String filename; private RealImage image = null; public ProxyImage(String filename) { this.filename = filename; } public void displayImage() { if (image == null) { image = new RealImage(filename); // load only on demand } image.displayImage(); } }
  • 10. Image Proxy (3 of 3)Image Proxy (3 of 3) class ProxyExample { public static void main(String[] args) { ArrayList<Image> images = new ArrayList<Image>(); images.add( new ProxyImage("HiRes_10GB_Photo1") ); images.add( new ProxyImage("HiRes_10GB_Photo2") ); images.add( new ProxyImage("HiRes_10GB_Photo3") ); images.get(0).displayImage(); // loading necessary images.get(1).displayImage(); // loading necessary images.get(0).displayImage(); // no loading necessary; already done // the third image will never be loaded - time saved! } }
  • 12. 12 Sample Context: Word ProcessorSample Context: Word Processor Paragraph Document Paragraph Image Document Draw() GetExtent() Store() Load() Glyph Text extent Draw() GetExtent() Store() Load() Paragraph fileName extent Draw() GetExtent() Store() Load() Image content extent Draw() GetExtent() Store() Load() Table
  • 13. 13 ForcesForces 1. The image is expensive to load1. The image is expensive to load 2. The complete image is not always2. The complete image is not always necessarynecessary 2MB 2KB optimize!
  • 16. Remote ProxyRemote Proxy  The Client and Real Subject are in different processesThe Client and Real Subject are in different processes or on different machines, and so a direct method callor on different machines, and so a direct method call will not workwill not work  The Proxy's job is to pass the method call acrossThe Proxy's job is to pass the method call across process or machine boundaries, and return the resultprocess or machine boundaries, and return the result to the client (with Broker's help)to the client (with Broker's help)
  • 17. Protection ProxyProtection Proxy  Different clients have different levels of accessDifferent clients have different levels of access privileges to an objectprivileges to an object  Clients access the object through a proxyClients access the object through a proxy  The proxy either allows or rejects a method callThe proxy either allows or rejects a method call depending on what method is being called anddepending on what method is being called and who is calling it (i.e., the client's identity)who is calling it (i.e., the client's identity)
  • 18. Additional UsesAdditional Uses  Read-only CollectionsRead-only Collections  Wrap collection object in a proxy that only allows read-onlyWrap collection object in a proxy that only allows read-only operations to be invoked on the collectionoperations to be invoked on the collection  All other operations throw exceptionsAll other operations throw exceptions  List Collections.unmodifiableList(List list);List Collections.unmodifiableList(List list);  Returns read-only List proxyReturns read-only List proxy  Synchronized CollectionsSynchronized Collections  Wrap collection object in a proxy that ensures only one thread atWrap collection object in a proxy that ensures only one thread at a time is allowed to access the collectiona time is allowed to access the collection  Proxy acquires lock before calling a method, and releases lockProxy acquires lock before calling a method, and releases lock after the method completesafter the method completes  List Collections.synchronizedList(List list);List Collections.synchronizedList(List list);  Returns a synchronized List proxyReturns a synchronized List proxy