Proxy Pattern (et Relata) (seen from someone still living in the '70, the '80 and, partly, in the '90) 1
Proxy Pattern Pattern Name and Classification (Kategorisierung) Intent (Zweck) Motivation/ Forces (Problem/Kontext/Umfeld) Implementation (Lösung/Umsetzung) Structure Applicability (Szenario/Verwendung) Pros & Cons (Vorteilen/Nachteilen) Related Patterns (Verweise) Code examples 2
Pattern Name and Classification Pattern Name: Proxy Pattern (Stellvertreter) Classification: Structural Pattern (structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.) 3
Intent Provide a surrogate or placeholder for another object to control access to it. Use an extra level of indirection to support distributed, controlled, or intelligent access. Add a wrapper and delegation to protect the real component from undue complexity. 4
Motivation/Problem You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are actually requested by the client. 5
Implementation Design a surrogate, or proxy, object that: instantiates the real object the first time the client makes a request of the proxy remembers the identity of this real object and forwards the instigating request to this real object. Then all subsequent requests are simply forwarded directly to the encapsulated real object. 6
Implementation Check list Identify the leverage or "aspect" that is best implemented as a wrapper or surrogate. Define an interface that will make the proxy and the original component interchangeable. Consider defining a Factory that can encapsulate the decision of whether a proxy or original object is desirable. The wrapper class holds a pointer to the real class and implements the interface. The pointer may be initialized at construction, or on first use. Each wrapper method contributes its leverage, and delegates to the wrappee object. 7
Structure By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client. 8
Applicability There are four common situations in which the Proxy pattern is applicable. 1)VirtualProxy: A virtual proxy is a placeholder for "expensive to create" objects. The real object is only created when a client first requests/accesses the object. 2)RemoteProxy: A remote proxy provides a local representative for an object that resides in a different address space. This is what the "stub" code in RPC and CORBA provides. 3)ProtectionProxy: A protective proxy controls access to a sensitive master object. The "surrogate" object checks that the caller has the access permissions required prior to forwarding the request. (e.g.: www-proxy) 4)SmartProxy: A smart proxy interposes additional actions when an object is accessed. Typical uses include: Counting the number of references to the real object so that it can be freed automatically when there are no more references (aka smart pointer), Change or augment the behavior of the instantiated object (useful with classes libraries we do not have the source code). Checking that the real object is locked before it is accessed to ensure that no other object can change it. 9
Pros & Cons Pro: As seen in Applications, with a Proxy we can implement aspects that are not related with the proper logic of the real object (such as security,logging, pooling caching and the likes) Cons: For each method in the realclass we have to implement a coresponding method in the proxy (possible solution: Dynamic Proxy) 10
Related Patterns Adapter provides a different interface to its subject. Proxy provides the same interface as its subject (or a subset, in the case of ProtectionProxy). Decorator provides an enhanced interface (adds one or more responsibility), whereas a proxy controls access to an object. Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests. 11
Code examples C++: Proxy in C++: Before and after Java:Proxy Pattern Java Example 12
Design Patterns Considered Harmful (Oh NO... NOT AGAIN!) 13
Design Patterns Considered Harmful First, let me quote Prof. Amrhein's slide #3s from DesignPatternEinfuehrung.pdf: Design Pattern sind unabhängig von der konkreten Programmiersprache. Das ermöglicht, dass man zunächst abstrakt über mögliche Lösungen sprechen kann. Damit kann auf hohem Abstraktions-Niveau über verschiedene Alternativen diskutiert werden, also ohne eine konkrete Lösung (Programmcode). And slide #4: Entwickler konnen durch das Kennen vieler Design Pattern dazu verleitet werden, moglichst viele Pattern zu verwenden und dabei ubersehen, dass in ihrem Fall vielleicht eine einfachere, elegantere Losung ohne den Einsatz von Design Pattern sinnvoller gewesen ware. Design Pattern konnen den Code unnotig aufblahen, da durch das Verwenden des Pattern (ev. unnotigerweise) ein allgemeineres Problem gelost wird. Entwurfsmuster garantieren nicht, dass der Entwurf gut ist. Insofern ist die Anwendung zu vieler oder ungeeigneter Entwurfsmuster ein Antimuster. 14
Design Patterns Considered Harmful 15
Design Patterns Considered Harmful Then let's see what Wikipedia says (This has always bothered me): - A design pattern is not a finished design that can be transformed directly into source or machine code. - By definition, a pattern must be programmed anew into each application that uses it. Since some authors see this as a step backward from software reuse as provided by components, researchers have worked to turn patterns into components.[...] Criticism The concept of design patterns has been criticized in several ways. The design patterns may just be a sign of some missing features of a given programming language (Java or C++ for instance). Peter Norvig demonstrates that 16 out of the 23 patterns in the Design Patterns book (that is primarily focused on C++) are simplified or eliminated (via direct language support) in Lisp or Dylan.[24] Related observations were made by Hannemann and Kiczales who implemented several of the 23 design patterns using an aspect-oriented programming language (AspectJ) [ ].[25] See also Paul Graham's essay "Revenge of the Nerds".[26] Moreover, inappropriate use of patterns may unnecessarily increase complexity.[27] [wikipedia: http://en.wikipedia.org/wiki/software_design_pattern] 16
Design Patterns Considered Harmful Paul Graham's essay "Revenge of the Nerds" (2002: considerations still valid!) Greenspun's Tenth Rule: Any sufficiently complicated C or Fortran program contains an ad hoc informally-specified bug-ridden slow implementation of half of Common Lisp. If you try to solve a hard problem, the question is not whether you will use a powerful enough language, but whether you will (a) use a powerful language, (b) write a de facto interpreter for one, or (c) yourself become a human compiler for one. [ ] For example, in the OO world you hear a good deal about "patterns". I wonder if these patterns are not sometimes evidence of case (c), the human compiler, at work. When I see patterns in my programs, I consider it a sign of trouble. The shape of a program should reflect only the problem it needs to solve. Any other regularity in the code is a sign, to me at least, that I'm using abstractions that aren't powerful enough-- often that I'm generating by hand the expansions of some macro that I need to write. [source: http://www.paulgraham.com/icad.html] 17
Design Patterns Considered Harmful References: http://perl.plover.com/yak/design/samples/slide001.html http://c2.com/cgi/wiki?designpatternsconsideredharmful http://www.perlmonks.org/?node_id=133399 http://blog.codinghorror.com/head-first-design-patterns/ http://blog.codinghorror.com/rethinking-design-patterns/ http://www.paulgraham.com/icad.html http://www.norvig.com/design-patterns/ http://www.dadhacker.com/blog/?p=1274 18
Design Patterns Considered Harmful "All problems in computer science can be solved by another level of indirection, except of course for the problem of too many indirections." David Wheeler(*) (*) another immortal quote from the late Prof. Wheeler is Compatibility means deliberately repeating other people's mistakes. 19