SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

Serialization & De-serialization in Java
Serialization & De-serialization in JavaSerialization & De-serialization in Java
Serialization & De-serialization in JavaInnovationM
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - ObjectsWebStackAcademy
 
Building an API with Django and Django REST Framework
Building an API with Django and Django REST FrameworkBuilding an API with Django and Django REST Framework
Building an API with Django and Django REST FrameworkChristopher Foresman
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate FrameworkMohit Kanwar
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state managementpriya Nithya
 
Java CRUD Mechanism with SQL Server Database
Java CRUD Mechanism with SQL Server DatabaseJava CRUD Mechanism with SQL Server Database
Java CRUD Mechanism with SQL Server DatabaseDudy Ali
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Djangomcantelon
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Understanding Web Cache
Understanding Web CacheUnderstanding Web Cache
Understanding Web CacheProdigyView
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch APIXcat Liu
 

What's hot (20)

Serialization & De-serialization in Java
Serialization & De-serialization in JavaSerialization & De-serialization in Java
Serialization & De-serialization in Java
 
Iterator
IteratorIterator
Iterator
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
Ajax Presentation
Ajax PresentationAjax Presentation
Ajax Presentation
 
sets and maps
 sets and maps sets and maps
sets and maps
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Building an API with Django and Django REST Framework
Building an API with Django and Django REST FrameworkBuilding an API with Django and Django REST Framework
Building an API with Django and Django REST Framework
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
 
Java CRUD Mechanism with SQL Server Database
Java CRUD Mechanism with SQL Server DatabaseJava CRUD Mechanism with SQL Server Database
Java CRUD Mechanism with SQL Server Database
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Django
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
La plateforme JEE
La plateforme JEELa plateforme JEE
La plateforme JEE
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Understanding Web Cache
Understanding Web CacheUnderstanding Web Cache
Understanding Web Cache
 
Java servlets
Java servletsJava servlets
Java servlets
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
 

Similar to 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 to 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
 

More from Chester Hartin

More from 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
 

Recently uploaded

Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 

Recently uploaded (20)

Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 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