8/06/2011

Design Pattern - Command

Definition
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

UML Class Diagram

Command: when and where use it
- The Command design pattern encapsulates an action or a request as an object. The classic usage of this pattern is a menu system where each command object represents an action and an associated undo action. Menu actions include menu items such as File | Open, File | Save, Edit | Copy, etc each of which gets mapped to its own command object. 

- All Commands implement the same interface, so they can be handled polymorphically.  Typically their interface includes methods such as Do and Undo (or Execute and Undo).  Areas where you find Command patterns are: menu command systems and in applications that require undo functionality (word processors, and sometimes in business applications that need database undo functionality).

Sample
- Command Interface

- Command class

- Receiver class

- Invoke class
 
Ref: Gang of Four tutorial

Design Pattern - Proxy

Definition
Provide a surrogate or placeholder for another object to control access to it.

UML Class Diagram

Proxy: when and where use it
- In object-oriented languages objects do the work they advertise through their public interface. Clients of these objects expect this work to be done quickly and efficiently.

- However, there are situations where an object is severely constrained and cannot live up to its responsibility. Typically this occurs when there is a dependency on a remote resource (a call to another computer for example) or when an object takes a long time to load. In situations like these you apply the Proxy pattern and create a proxy object that stands in? for the original object. The Proxy forwards the request to a target object.  The interface of the Proxy object is the same as the original object and clients may not even be aware they are dealing with a proxy rather than the real object. 

- The proxy pattern is meant to provide a surrogate or placeholder for another object to control access to it. There are 3 different types of proxies:
    + Remote proxies are responsible for encoding a request and for forwarding the encoded request to a real object in a different address space (app domain,
process, or machine)
    + Virtual proxies may cache additional information about a real object so that they can postpone accessing it (this process is known by many names, such as, just-in-time loading, on-demand loading, or lazy loading)
    + Protection proxies check that the caller has the proper access permissions to perform the request.  

Sample
- Interface

- Object

- Proxy


Ref: Gang of Four tutorial