Design Patterns
  • Introduction
  • Proto-Pattern
  • Anti-pattern
  • OO Design Principles
  • Classification
  • Creational Design Patterns
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Prototype
  • Structural design patterns
    • Adapter
    • Bridge
    • Composite
    • Decorator
    • Facade
    • Flyweight
    • Proxy
  • Behavioural Design Pattern
    • Chain of Responsibility
    • Command
    • Interpreter
    • Iterator
    • Mediator
    • Memento
    • Observer
    • State
    • Strategy
    • Template Method
    • Visitor
  • Concurrency Design Pattern
  • Architectural Design Pattern
  • Modern Desing Patterns
Powered by GitBook
On this page

Was this helpful?

  1. Structural design patterns

Proxy

An object representing another object.

  • Proxy provides a surrogate or placeholder for another object to control access to it.

  • Proxy means 'in place of' or 'representing' or 'on behalf of'.

  • The proxy is the object that is being called by the client to access the real object behind the scene.

  • In this pattern, a class represents functionality of another class.

  • Most frequently used in JavaScript.

EX:
function GeoCoder() {
 
    this.getLatLng = function(address) {
        
        if (address === "Amsterdam") {
            return "52.3700° N, 4.8900° E";
        } else if (address === "London") {
            return "51.5171° N, 0.1062° W";
        } else if (address === "Paris") {
            return "48.8742° N, 2.3470° E";
        } else if (address === "Berlin") {
            return "52.5233° N, 13.4127° E";
        } else {
            return "";
        }
    };
}
 
function GeoProxy() {
    var geocoder = new GeoCoder();
    var geocache = {}; 
    return {
        getLatLng: function(address) {
            if (!geocache[address]) {
                geocache[address] = geocoder.getLatLng(address);
            }
            return geocache[address];
        },
        getCount: function() {
            var count = 0;
            for (var code in geocache) { count++; }
            return count;
        }
    };
};

var geo = new GeoProxy();
 
    // geolocation requests 
    geo.getLatLng("Paris");
    geo.getLatLng("London");
    geo.getLatLng("London");
    geo.getLatLng("London");
    geo.getLatLng("London");
    geo.getLatLng("Amsterdam");
    geo.getLatLng("Amsterdam");
    geo.getLatLng("Amsterdam");
    geo.getLatLng("Amsterdam");
    geo.getLatLng("London");
    geo.getLatLng("London"); 
    console.log("\nCache size: " + geo.getCount());

Real time Ex:

PreviousFlyweightNextBehavioural Design Pattern

Last updated 5 years ago

Was this helpful?

Real time Example for Proxy Pattern