SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

[2020 CVPR Efficient DET paper review]
[2020 CVPR Efficient DET paper review][2020 CVPR Efficient DET paper review]
[2020 CVPR Efficient DET paper review]taeseon ryu
 
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것흥배 최
 
Lecture 15 monkey banana problem
Lecture 15 monkey banana problemLecture 15 monkey banana problem
Lecture 15 monkey banana problemHema Kashyap
 
Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questionsUmar Ali
 
Message Queuing (MSMQ)
Message Queuing (MSMQ)Message Queuing (MSMQ)
Message Queuing (MSMQ)Senior Dev
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design PatternVarun Arora
 
Python Fundamentals
Python FundamentalsPython Fundamentals
Python FundamentalsSherif Rasmy
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundationKevlin Henney
 
Deep Learning A-Z™: Convolutional Neural Networks (CNN) - Step 1: Convolution...
Deep Learning A-Z™: Convolutional Neural Networks (CNN) - Step 1: Convolution...Deep Learning A-Z™: Convolutional Neural Networks (CNN) - Step 1: Convolution...
Deep Learning A-Z™: Convolutional Neural Networks (CNN) - Step 1: Convolution...Kirill Eremenko
 
Set data structure
Set data structure Set data structure
Set data structure Tech_MX
 
Binary search tree
Binary search treeBinary search tree
Binary search treeKousalya M
 
게임 서버 성능 분석하기
게임 서버 성능 분석하기게임 서버 성능 분석하기
게임 서버 성능 분석하기iFunFactory Inc.
 

Tendances (20)

[2020 CVPR Efficient DET paper review]
[2020 CVPR Efficient DET paper review][2020 CVPR Efficient DET paper review]
[2020 CVPR Efficient DET paper review]
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Iterator
IteratorIterator
Iterator
 
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
 
Lecture 15 monkey banana problem
Lecture 15 monkey banana problemLecture 15 monkey banana problem
Lecture 15 monkey banana problem
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
 
Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questions
 
Visual reasoning
Visual reasoningVisual reasoning
Visual reasoning
 
Timestamp protocols
Timestamp protocolsTimestamp protocols
Timestamp protocols
 
Message Queuing (MSMQ)
Message Queuing (MSMQ)Message Queuing (MSMQ)
Message Queuing (MSMQ)
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
 
Python Fundamentals
Python FundamentalsPython Fundamentals
Python Fundamentals
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Deep Learning A-Z™: Convolutional Neural Networks (CNN) - Step 1: Convolution...
Deep Learning A-Z™: Convolutional Neural Networks (CNN) - Step 1: Convolution...Deep Learning A-Z™: Convolutional Neural Networks (CNN) - Step 1: Convolution...
Deep Learning A-Z™: Convolutional Neural Networks (CNN) - Step 1: Convolution...
 
Set data structure
Set data structure Set data structure
Set data structure
 
Daa unit 2
Daa unit 2Daa unit 2
Daa unit 2
 
Binary search tree
Binary search treeBinary search tree
Binary search tree
 
게임 서버 성능 분석하기
게임 서버 성능 분석하기게임 서버 성능 분석하기
게임 서버 성능 분석하기
 

Similaire à 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
 

Similaire à 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
 

Plus de Chester Hartin

Plus 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
 

Dernier

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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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
 
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
 

Dernier (20)

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...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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
 
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
 

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