SlideShare une entreprise Scribd logo
1  sur  5
Télécharger pour lire hors ligne
Gang of Four – Proxy Design Pattern
http://idiotechie.com/?p=1112                                                            November 12, 2012



0
Posted by IdioTechie on November 10, 2012

Descript ion:
Proxy is another Structural design pattern which works ‘on behalf of’ or ‘in place of’
another object in order to access the later.

                                                       ie. com
                                               ech
When t o use t his pat t ern?
Proxy pattern is used when we need to create a wrapper to cover the main object’s complexity
                                            ot
                                       idi
from the client.

What are t he usage scenarios? //

    Virtual Proxy – Imagine t
                                p:
                              tsituation where there is multiple database call to extract huge size
                          hexpensive operation we can possibly use the proxy pattern which
                            a
                     ©
    image. Since this is an
    would create multiple proxies and point to the huge size memory consuming object for
       further processing. The real object gets created only when a client first requests/accesses
       the object and after that we can just refer to the proxy to reuse the object. This avoids
       duplication of the object and hence saving memory.
       Remote Proxy – A remote proxy can be thought about the stub in the RPC call. The remote
       proxy provides a local representation of the object which is present in the different address
       location. Another example can be providing interface for remote resources such as web
       service or REST resources.
       Protective Proxy – The protective proxy acts as an authorisation layer to verify if the actual
       user has access to appropriate content. An example can be thought about the proxy server
       which provides restrictive internet access in office. Only the websites and contents which are
       valid will be allowed and the remaining ones will be blocked.
       Smart Proxy – A smart proxy provides additional layer of security by interposing specific
       actions when the object is accessed. An example can be to check if the real object is locked
       before it is accessed to ensure that no other object can change it.

St ruct ure:

Part icipant s:
Part icipant s:

      Subject – This object defines the common
      interface for RealSubject and Proxy so that a
      Proxy can be used anywhere a RealSubject is
      expected.
      Proxy – It maintains a reference to the
      RealSubject so that Proxy can access it. It also
      implements the same interface as the
      RealSubject so that Proxy can be used in place
      of RealSubject. Proxy also controls the access
      to the RealSubject and can create or delete
                                                         ie. com
                                              ech
      this object.


                                         iot
     RealSubject – This refers the main object

                                   //id
     which the proxy represents.                                Proxy Design Pattern Structure

Example:
                          ht  tp: article. The first one will be virtual proxy pattern and the other
We will discuss two examples in this
one for protection proxy pattern.
Virtual Proxy Example:©
As mentioned earlier virtual proxy is useful to save expensive memory resources. Let’s take a
scenario where the real image contains a huge size data which clients needs to access. To save
our resources and memory the implementation will be as below:

      Create an interface which will be accessed by the client. All its methods will be implemented
      by the ProxyImage class and RealImage class.
      RealImage runs on the different system and contains the image information is accessed from
      the database.
      The ProxyImage which is running on a different system can represent the RealImage in the
      new system. Using the proxy we can avoid multiple loading of the image.

Class Diagram:

Code Example:

Image.java


public interface Image {
 public void showImage();
}


RealImage.java


                                                                    Virtual Proxy Example
public class RealImage implements Image {
 private String fileName = null;
 public RealImage(String strFileName){
 this.fileName = strFileName;
 }
 @Override
 public void showImage() {
 System.out.println(" Show Image:" +fileName);
 }

                                                         com
}

                                                     ie.
ProxyImage.java

                                           ot ech
                                  :// idi
public class ProxyImage implements Image {

                            ttp
 private RealImage img= null;
                          h
 private String fileName = null;
 public ProxyImage(String strFileName) {
                      ©
 this.fileName = strFileName;
 }
 /*
 * (non-Javadoc)
 * @see com.proxy.virtualproxy.Image#showImage()
 */
 @Override
 public void showImage() {
 if(img == null){
 img = new RealImage(fileName);
 }
 img.showImage();
 }
}


Client.java


public class Client {
public static void main(String[] args) {
 final Image img1 = new ProxyImage(" Image***1" );
 final Image img2 = new ProxyImage(" Image***2" );
 img1.showImage();
 img2.showImage();
 }
}


Protection Proxy Example:

      Let’s assume that company ABC starts a new policy that employees will now be prohibited
      internet access based on their roles. All external emails websites will be blocked. In such
situation we create InternetAccess interface which consists of operation
     grantInternetAccess().
     The RealInternetAccess class which allows of internet access for all. However to restrict this
     access we will use ProxyInternetAccess class which will check user’s role and grant access
     based on their roles.

Class Diagram:

Code Example:

InternetAccess:
                                                     ie. com
public interface InternetAccess {
                                          ot ech
                                     idi
 public void grantInternetAccess();
}
                                 ://
RealInternetAccess.java    h ttp
                     ©
                                                                 Protection Proxy Example



public class RealInternetAccess implements InternetAccess {
 private String employeeName = null;
 public RealInternetAccess(String empName) {
 this.employeeName = empName;
 }
 @Override
 public void grantInternetAccess() {
 System.out.println(" Internet Access granted for employee: "
 + employeeName);
 }
}


ProxyInternetAccess.java


public class RealInternetAccess implements InternetAccess {
 private String employeeName = null;
 public RealInternetAccess(String empName) {
 this.employeeName = empName;
 }
 @Override
 public void grantInternetAccess() {
 System.out.println(" Internet Access granted for employee: "
 + employeeName);
 }
}
Client.java


public static void main(String[] args) {
 InternetAccess ia = new ProxyInternetAccess(" Idiotechie" );
 ia.grantInternetAccess();
 }


Benef it s:
                                                            om
                                                          cseen in the above example is about
    security.
                                               ch   ie.
    One of the advantages of Proxy pattern as you have

                                            t ewhich might be huge size and memory intensive.
                                     id ioof the application.
    This pattern avoids duplication of objects
    This in turn increases the performance
                                   //about security by installing the local code proxy (stub) in the
                          ht  tp: the server with help of the remote code.
    The remote proxy also ensures
    client machine and then accessing
                      ©
Drawbacks/Consequences:
This pattern introduces another layer of abstraction which sometimes may be an issue if the
RealSubject code is accessed by some of the clients directly and some of them might access the
Proxy classes. This might cause disparate behaviour.

Int erest ing point s:

      There are few differences between the related patterns. Like Adapter pattern gives a
      different interface to its subject, while Proxy patterns provides the same interface from the
      original object but the decorator provides an enhanced interface. Decorator pattern adds
      additional behaviour at runtime.
      Proxy used in Java API: java.rmi.*;

Please don’t forget to leave your comments. In case you like this article please share this articles
for your friends through the social networking links.

Download Sample Code:




Filed in: Core Java, Design Pattern, Java, Random Tags: design pattern, download, gang of,
gang of four, GoF, idiotechie, Java, protection proxy, Proxy, proxy design pattern, remote proxy,
smart proxy, virtual proxy

Contenu connexe

En vedette

CMC 2.0
CMC 2.0CMC 2.0
CMC 2.0saugch
 
Personal Mindset To Change
Personal Mindset To ChangePersonal Mindset To Change
Personal Mindset To Changenick_lim
 
Understanding transport-layer_security__ssl
Understanding transport-layer_security__sslUnderstanding transport-layer_security__ssl
Understanding transport-layer_security__sslMainak Goswami
 
Rotaract St Andrews Club Overview Sept '13
Rotaract St Andrews Club Overview Sept '13Rotaract St Andrews Club Overview Sept '13
Rotaract St Andrews Club Overview Sept '13Ioanid Nagy-Vizitiu
 
Rotary Presentation by Diego Carillo
Rotary Presentation by Diego CarilloRotary Presentation by Diego Carillo
Rotary Presentation by Diego CarilloIoanid Nagy-Vizitiu
 
Allenamento scuola calcio
Allenamento scuola calcioAllenamento scuola calcio
Allenamento scuola calcioDavide Catti
 
Step by step guide for creating wordpress plugin
Step by step guide for creating wordpress pluginStep by step guide for creating wordpress plugin
Step by step guide for creating wordpress pluginMainak Goswami
 
Appoquinimink school district
Appoquinimink school districtAppoquinimink school district
Appoquinimink school districtNancy_P
 
Rotaract Presentation by Sofia Forster
Rotaract Presentation by Sofia ForsterRotaract Presentation by Sofia Forster
Rotaract Presentation by Sofia ForsterIoanid Nagy-Vizitiu
 

En vedette (11)

CMC 2.0
CMC 2.0CMC 2.0
CMC 2.0
 
Personal Mindset To Change
Personal Mindset To ChangePersonal Mindset To Change
Personal Mindset To Change
 
Understanding transport-layer_security__ssl
Understanding transport-layer_security__sslUnderstanding transport-layer_security__ssl
Understanding transport-layer_security__ssl
 
Rapor1
Rapor1Rapor1
Rapor1
 
Rotaract St Andrews Club Overview Sept '13
Rotaract St Andrews Club Overview Sept '13Rotaract St Andrews Club Overview Sept '13
Rotaract St Andrews Club Overview Sept '13
 
Rotary Presentation by Diego Carillo
Rotary Presentation by Diego CarilloRotary Presentation by Diego Carillo
Rotary Presentation by Diego Carillo
 
Allenamento scuola calcio
Allenamento scuola calcioAllenamento scuola calcio
Allenamento scuola calcio
 
Step by step guide for creating wordpress plugin
Step by step guide for creating wordpress pluginStep by step guide for creating wordpress plugin
Step by step guide for creating wordpress plugin
 
Dg khan
Dg khanDg khan
Dg khan
 
Appoquinimink school district
Appoquinimink school districtAppoquinimink school district
Appoquinimink school district
 
Rotaract Presentation by Sofia Forster
Rotaract Presentation by Sofia ForsterRotaract Presentation by Sofia Forster
Rotaract Presentation by Sofia Forster
 

Similaire à Gang of four Proxy Design Pattern

Proxy Design Patterns
Proxy Design PatternsProxy Design Patterns
Proxy Design PatternsZafer Genc
 
Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2Savio Sebastian
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805LearningTech
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02Sven Ruppert
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01Tony Frame
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDiego Lewin
 
Flex3 Deep Dive Final
Flex3 Deep Dive FinalFlex3 Deep Dive Final
Flex3 Deep Dive FinalRJ Owen
 
Unit8 java
Unit8 javaUnit8 java
Unit8 javamrecedu
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core ConceptsDivyang Bhambhani
 
Android architecture
Android architecture Android architecture
Android architecture Trong-An Bui
 
JAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp conceptsJAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp conceptsRahul Malhotra
 
XPages Blast - ILUG 2010
XPages Blast - ILUG 2010XPages Blast - ILUG 2010
XPages Blast - ILUG 2010Tim Clark
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java ProgrammingRaveendra R
 
Advanced Web Development
Advanced Web DevelopmentAdvanced Web Development
Advanced Web DevelopmentRobert J. Stein
 

Similaire à Gang of four Proxy Design Pattern (20)

Proxy Design Patterns
Proxy Design PatternsProxy Design Patterns
Proxy Design Patterns
 
Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2Design Patterns - Part 2 of 2
Design Patterns - Part 2 of 2
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
 
.Net template solution architecture
.Net template solution architecture.Net template solution architecture
.Net template solution architecture
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01Googleappengineintro 110410190620-phpapp01
Googleappengineintro 110410190620-phpapp01
 
Web workers
Web workersWeb workers
Web workers
 
Web workers
Web workersWeb workers
Web workers
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
Flex3 Deep Dive Final
Flex3 Deep Dive FinalFlex3 Deep Dive Final
Flex3 Deep Dive Final
 
Unit8 java
Unit8 javaUnit8 java
Unit8 java
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core Concepts
 
Android architecture
Android architecture Android architecture
Android architecture
 
JAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp conceptsJAVA design patterns and Basic OOp concepts
JAVA design patterns and Basic OOp concepts
 
Tomcat + other things
Tomcat + other thingsTomcat + other things
Tomcat + other things
 
XPages Blast - ILUG 2010
XPages Blast - ILUG 2010XPages Blast - ILUG 2010
XPages Blast - ILUG 2010
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java Programming
 
Advanced Web Development
Advanced Web DevelopmentAdvanced Web Development
Advanced Web Development
 

Gang of four Proxy Design Pattern

  • 1. Gang of Four – Proxy Design Pattern http://idiotechie.com/?p=1112 November 12, 2012 0 Posted by IdioTechie on November 10, 2012 Descript ion: Proxy is another Structural design pattern which works ‘on behalf of’ or ‘in place of’ another object in order to access the later. ie. com ech When t o use t his pat t ern? Proxy pattern is used when we need to create a wrapper to cover the main object’s complexity ot idi from the client. What are t he usage scenarios? // Virtual Proxy – Imagine t p: tsituation where there is multiple database call to extract huge size hexpensive operation we can possibly use the proxy pattern which a © image. Since this is an would create multiple proxies and point to the huge size memory consuming object for further processing. The real object gets created only when a client first requests/accesses the object and after that we can just refer to the proxy to reuse the object. This avoids duplication of the object and hence saving memory. Remote Proxy – A remote proxy can be thought about the stub in the RPC call. The remote proxy provides a local representation of the object which is present in the different address location. Another example can be providing interface for remote resources such as web service or REST resources. Protective Proxy – The protective proxy acts as an authorisation layer to verify if the actual user has access to appropriate content. An example can be thought about the proxy server which provides restrictive internet access in office. Only the websites and contents which are valid will be allowed and the remaining ones will be blocked. Smart Proxy – A smart proxy provides additional layer of security by interposing specific actions when the object is accessed. An example can be to check if the real object is locked before it is accessed to ensure that no other object can change it. St ruct ure: Part icipant s:
  • 2. Part icipant s: Subject – This object defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected. Proxy – It maintains a reference to the RealSubject so that Proxy can access it. It also implements the same interface as the RealSubject so that Proxy can be used in place of RealSubject. Proxy also controls the access to the RealSubject and can create or delete ie. com ech this object. iot RealSubject – This refers the main object //id which the proxy represents. Proxy Design Pattern Structure Example: ht tp: article. The first one will be virtual proxy pattern and the other We will discuss two examples in this one for protection proxy pattern. Virtual Proxy Example:© As mentioned earlier virtual proxy is useful to save expensive memory resources. Let’s take a scenario where the real image contains a huge size data which clients needs to access. To save our resources and memory the implementation will be as below: Create an interface which will be accessed by the client. All its methods will be implemented by the ProxyImage class and RealImage class. RealImage runs on the different system and contains the image information is accessed from the database. The ProxyImage which is running on a different system can represent the RealImage in the new system. Using the proxy we can avoid multiple loading of the image. Class Diagram: Code Example: Image.java public interface Image { public void showImage(); } RealImage.java Virtual Proxy Example
  • 3. public class RealImage implements Image { private String fileName = null; public RealImage(String strFileName){ this.fileName = strFileName; } @Override public void showImage() { System.out.println(" Show Image:" +fileName); } com } ie. ProxyImage.java ot ech :// idi public class ProxyImage implements Image { ttp private RealImage img= null; h private String fileName = null; public ProxyImage(String strFileName) { © this.fileName = strFileName; } /* * (non-Javadoc) * @see com.proxy.virtualproxy.Image#showImage() */ @Override public void showImage() { if(img == null){ img = new RealImage(fileName); } img.showImage(); } } Client.java public class Client { public static void main(String[] args) { final Image img1 = new ProxyImage(" Image***1" ); final Image img2 = new ProxyImage(" Image***2" ); img1.showImage(); img2.showImage(); } } Protection Proxy Example: Let’s assume that company ABC starts a new policy that employees will now be prohibited internet access based on their roles. All external emails websites will be blocked. In such
  • 4. situation we create InternetAccess interface which consists of operation grantInternetAccess(). The RealInternetAccess class which allows of internet access for all. However to restrict this access we will use ProxyInternetAccess class which will check user’s role and grant access based on their roles. Class Diagram: Code Example: InternetAccess: ie. com public interface InternetAccess { ot ech idi public void grantInternetAccess(); } :// RealInternetAccess.java h ttp © Protection Proxy Example public class RealInternetAccess implements InternetAccess { private String employeeName = null; public RealInternetAccess(String empName) { this.employeeName = empName; } @Override public void grantInternetAccess() { System.out.println(" Internet Access granted for employee: " + employeeName); } } ProxyInternetAccess.java public class RealInternetAccess implements InternetAccess { private String employeeName = null; public RealInternetAccess(String empName) { this.employeeName = empName; } @Override public void grantInternetAccess() { System.out.println(" Internet Access granted for employee: " + employeeName); } }
  • 5. Client.java public static void main(String[] args) { InternetAccess ia = new ProxyInternetAccess(" Idiotechie" ); ia.grantInternetAccess(); } Benef it s: om cseen in the above example is about security. ch ie. One of the advantages of Proxy pattern as you have t ewhich might be huge size and memory intensive. id ioof the application. This pattern avoids duplication of objects This in turn increases the performance //about security by installing the local code proxy (stub) in the ht tp: the server with help of the remote code. The remote proxy also ensures client machine and then accessing © Drawbacks/Consequences: This pattern introduces another layer of abstraction which sometimes may be an issue if the RealSubject code is accessed by some of the clients directly and some of them might access the Proxy classes. This might cause disparate behaviour. Int erest ing point s: There are few differences between the related patterns. Like Adapter pattern gives a different interface to its subject, while Proxy patterns provides the same interface from the original object but the decorator provides an enhanced interface. Decorator pattern adds additional behaviour at runtime. Proxy used in Java API: java.rmi.*; Please don’t forget to leave your comments. In case you like this article please share this articles for your friends through the social networking links. Download Sample Code: Filed in: Core Java, Design Pattern, Java, Random Tags: design pattern, download, gang of, gang of four, GoF, idiotechie, Java, protection proxy, Proxy, proxy design pattern, remote proxy, smart proxy, virtual proxy