Wednesday, November 28, 2012

Null Object Design Pattern

Although they are lots of books and articles about Design Patterns, yet I like to share my point of view about common design patterns with you, and would be happy to have your thoughts or questions on comments. This post introduces Null Object design pattern.

Definition
A Null Object is an object with defined neutral ("null") behavior. The Null Object design pattern describes the uses of such objects and their behavior (or lack thereof). (Wikipedia)


  • AbstractClass defines abstract primitive operations for client’s collaborator that concrete implementations have to define. It optionally implements default behavior for the interface common to all classes, as appropriate.
  • RealClass implements AbstractClass performing some real actions that client expects.
  • NullClass implements AbstractClass and does nothing in order to provide a non-null object to the client that can be substituted for a real object
  • Client has a reference to abstract class implementation and collaborates with it and does not care if the implementation is a null object or an real object.

If some clients expect the null object to do nothing one way and some another, multiple NullObject classes will be required. If the do nothing behavior must be customized at run time. A Null Object does not transform to become a Real Object. If the object may decide to stop providing do nothing behavior and start providing real behavior, it is not a null object. The null behavior is not designed to be mixed into an object that needs some do nothing behavior. It is designed for a class which delegates to a collaborator all of the behavior that may or may not be do nothing behavior.

Applicability
  • The Null Object Pattern is used to avoid special if blocks for do nothing code, by putting the “do nothing” code in the Null Object which becomes responsible for doing nothing. The client is not aware anymore if the real object or the null object is called so the ' if ' section is removed from client implementation.
  • Some collaborator instances should do nothing
  • Can  be used to act as a stub for testing
  • Can be used to remove old functionality by replacing it with null objects, as a result the existing code does not need to be touched.

Consequences
  • A Null Object is predictable and has no side effects: it does nothing.
  • Provides intelligent do nothing behavior and hiding the details from its collaborators
  • Provide an object as a surrogate for the lack of an object of a given type.
  •  Clients can treat real collaborators and null collaborators uniformly.

Downsides
  • Can make errors/bugs appear as normal program execution.
  • Can be difficult to implement if various clients do not agree on how the null object should do nothing as when your AbstractObject interface is not well defined.

Sample Code

Related Patterns
  • Null Object pattern can be regarded as a special case of the State and the Strategy pattern.
  • Null Object  pattern is more likely to be used in conjunction with the Factory Method pattern. 
  • Null Object class is often implemented as a Singleton since a null object usually does not have any state.
  • Null Object can be used to allow a Visitor to safely visit a hierarchy and handle the null situation.
  • The use of a Null Object can be similar to that of a Proxy, but the two patterns have different purposes. A proxy provides a level of indirection when accessing a real subject, thus controlling access to the subject. A null collaborator does not hide a real object and control access to it, it replaces the real object. A proxy may eventually mutate to start acting like a real subject. A null object will not mutate to start providing real behavior, it will always provide do nothing behavior.

References
http://en.wikipedia.org/wiki/Null_Object_pattern
http://sourcemaking.com/design_patterns/null_object
http://www.oodesign.com/null-object-pattern.html

Further readings
http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx
http://blog.dezfowler.com/2010/09/null-object-pattern-and-maybe-monad.html
http://www.cs.oberlin.edu/~jwalker/nullObjPattern/

Sunday, November 25, 2012

Builder Design Pattern

Although they are lots of books and articles about Design Patterns, yet I like to share my point of view about common design patterns with you, and would be happy to have your thoughts or questions on comments. This post introduces GoF Builder design pattern.

Definition
Separate the construction of a complex object from its representation so that the same construction process can create different representations. (dofactory)


  • Builder specifies an abstract interface for creating parts of a Product object
  • ConcreteBuilder constructs and assembles parts of the product by implementing the Builder interface. It defines and keeps track of the representation it creates and provides an interface for retrieving the product
  • Director constructs an object using the Builder interface
  • Product represents the complex object under construction. ConcreteBuilder builds the product's internal representation and defines the process by which it's assembled. It  includes classes that define the constituent parts, including interfaces for assembling the parts into the final result

Applicability
  • An application needs to create the elements of a complex aggregate.
  • The creation algorithm of a complex object is independent from the parts that actually compose the object and  system needs to allow different representations for the objects that are being built. 
  • Builders are good candidates for a fluent interface.
  • An example of the pattern in .NET and also Java API is StringBuilder. 

Consequences
  • Separate the construction of a complex object from its representation
  • Same construction process can create different representation
  • Having control over the creation process at runtime

Downsides
  • I do not see a particular downside for this pattern, However, builder pattern is not a good choice if the object to construct needs to be immutable.

Sample Code
Classic builder pattern example


Fluent interface builder example


Related Patterns
  • Sometimes creational patterns are complementory: Builder can use one of the other patterns to implement which components get built. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.
  • Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
  • Builder often builds a Composite.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.

References
http://www.dofactory.com/Patterns/PatternBuilder.aspx
http://en.wikipedia.org/wiki/Builder_pattern
http://sourcemaking.com/design_patterns/builder
http://www.oodesign.com/builder-pattern.html
http://java.dzone.com/articles/design-patterns-builder
http://www.avajava.com/tutorials/lessons/builder-pattern.html
http://stefanoricciardi.com/2010/04/14/a-fluent-builder-in-c/

Further readings
http://en.wikipedia.org/wiki/Fluent_interface
http://ayende.com/blog/159362/design-patterns-in-the-test-of-time-builder
http://javapapers.com/design-patterns/builder-pattern/
http://www.codeproject.com/Articles/42415/Builder-Design-Pattern
http://www.blackwasp.co.uk/Builder.aspx
http://weblogs.asp.net/arturtrosin/archive/2009/04/13/builder-pattern-through-fluent-interface.aspx
http://mattdavey.me/2012/03/08/practical-applications-of-the-adaptive-interface-pattern-the-fluent-builder-context/
http://andrevianna.com/blog/index.php/2010/08/guidelines-to-fluent-interface-design-in-c-part-1/

Abstract Factory Design Pattern

Although they are lots of books and articles about Design Patterns, yet I like to share my point of view about common design patterns with you, and would be happy to have your thoughts or questions on comments. This post introduces GoF Abstract Factory design pattern.

Definition
Provide an interface for creating families of related or dependent objects without specifying their concrete classes. (dofactory)


  • AbstractFactory declares an interface for operations that create abstract products
  • ConcreteFactory implements the operations to create concrete product objects
  • AbstractProduct declares an interface for a type of product object
  • Product defines a product object to be created by the corresponding concrete factory implements the AbstractProduct interface
  • Client uses interfaces declared by AbstractFactory and AbstractProduct classes

Applicability
  • We should use the Abstract Factory design pattern when:
    • The system needs to be independent from the way the products it works with are created.
    • The system is or should be configured to work with multiple families of products.
    • A family of products is designed to work only all together.
    • The creation of a library of products is needed, for which is relevant only the interface, not the implementation, too.

Consequences
  • Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
  • Abstract Factory is a super-factory which creates other factories (Factory of factories).

Downsides
  • Adding new products to the existing factories is difficult, because the Abstract Factory interface uses a fixed set of products that can be created. That is why adding a new product would mean extending the factory interface, which involves changes in the AbstractFactory class and all its subclasses. 

Sample Code 

Related Patterns
  • Sometimes creational patterns are competitors: there are cases when either Prototype or Abstract Factory could be used profitably. At other times they are complementary: Abstract Factory might store a set of Prototypes from which to clone and return product objects, Builder can use one of the other patterns to implement which components get built. Abstract Factory, Builder, and Prototype can use Singleton in their implementation.
  • Abstract Factory, Builder, and Prototype define a factory object that’s responsible for knowing and creating the class of product objects, and make it a parameter of the system. Abstract Factory has the factory object producing objects of several classes. Builder has the factory object building a complex product incrementally using a correspondingly complex protocol. Prototype has the factory object (aka prototype) building a product by copying a prototype object.
  • Abstract Factory classes are often implemented with Factory Methods, but they can also be implemented using Prototype.

References
http://www.dofactory.com/Patterns/PatternAbstract.aspx
http://sourcemaking.com/design_patterns/abstract_factory
http://www.oodesign.com/prototype-pattern.html
http://java.dzone.com/articles/design-patterns-abstract-factory

Further readings
http://en.wikipedia.org/wiki/Abstract_factory_pattern
http://www.avajava.com/tutorials/lessons/abstract-factory-pattern.html
http://www.nileshgule.com/2012/03/abstract-factory-design-pattern.html

Saturday, November 24, 2012

Factory Method Design Pattern

Although they are lots of books and articles about Design Patterns, yet I like to share my point of view about common design patterns with you, and would be happy to have your thoughts or questions on comments. This post introduces GoF Factory Method design pattern.

Definition
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. (dofactory)




  • Product defines the interface of objects the factory method creates
  • ConcreteProduct  implements the Product interface
  • Creator declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object. Creator may call the factory method to create a Product object.
  • ConcreteCreator overrides the factory method to return an instance of a ConcreteProduct.


Applicability
  • When a class can not anticipate the type of the objects it is supposed to create. In other words, when a client does not know what concrete classes it will be required to create at runtime, but just wants to get a class that will do the job. If the classes doesn't extend common base class or interface they can not be used in a factory design template.
  • When a class wants its subclasses to be the ones to specific the type of a newly created object.
  • The creation of an object precludes its reuse without significant duplication of code.
  • The creation of an object requires access to information or resources that should not be contained within the composing class
  • The lifetime management of the generated objects must be centralized to ensure a consistent behavior within the application

Consequences
  • Lets a class defer instantiation to subclasses.
  • Makes a design more customizable and only a little more complicated. 
  • The advantage of a Factory Method is that it can return the same instance multiple times, or can return a subclass rather than an object of that exact type.
  • The main reason for which the factory pattern is used is that it introduces a separation between the application and a family of classes (it introduces weak coupling instead of tight coupling hiding concrete classes from the application). It provides a simple way of extending the family of products with minor changes in application code.
  • Some Factory Method advocates recommend that as a matter of language design (or failing that, as a matter of style) absolutely all constructors should be private or protected. It’s no one else’s business whether a class manufactures a new object or recycles an old one.
  • The new operator considered harmful. There is a difference between requesting an object and creating one. The new operator always creates an object, and fails to encapsulate object creation. A Factory Method enforces that encapsulation, and allows an object to be requested without inextricable coupling to the act of creation.

Downsides
  • The factory has to be used for a family of objects. If the classes does not extend common base class or interface they can not be used in a factory design template. If we do extend the class (e.g., by making the constructor protected—this is risky but feasible), the subclass must provide its own re-implementation of all factory methods with exactly the same signatures. 
  • Refactoring an existing class to use factories breaks existing clients. 
  • It might be overcomplicated.

Sample Code 

Related Patterns
  • Abstract Factory classes are often implemented with Factory Methods, but they can be implemented using Prototype
  • Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation.with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition
  • Factory Methods are usually called within Template Methods.
  • Factory Method 'creation' is through inheritance and Prototype creation is through delegation.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
  • Prototype does not require subclassing, but it does require an Initialize operation. Factory Method requires subclassing, but does not require Initialize.

References
http://www.dofactory.com/Patterns/PatternFactory.aspx
http://en.wikipedia.org/wiki/Factory_method_pattern
http://sourcemaking.com/design_patterns/factory_method
http://www.oodesign.com/prototype-pattern.html
http://java.dzone.com/articles/design-patterns-factory

Further readings
http://www.avajava.com/tutorials/lessons/factory-pattern.html
http://www.blackwasp.co.uk/FactoryMethod.aspxds

Prototype Design Pattern

Although they are lots of books and articles about Design Patterns, yet I like to share my point of view about common design patterns with you, and would be happy to have your thoughts or questions on comments. This post introduces GoF Prototype design pattern.

Definition

Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype. (dofactory



  • Prototype declares an interface for cloning itself
  • ConcretePrototype  implements an operation for cloning itself
  • Client creates a new object by asking a prototype to clone itself

Using a prototype manager
When the application uses a lot of prototypes that can be created and destroyed dynamically, a registry of available prototypes should be kept. This registry is called the prototype manager and it should implement operations for managing registered prototypes like registering a prototype under a certain key, searching for a prototype with a given key, removing one from the register, etc. The clients will use the interface of the prototype manager to handle prototypes at run-time and will ask for permission before using the Clone() method. There is not much difference between an implementation of a prototype which uses a prototype manager and a factory method implemented using class registration mechanism. Maybe the only difference consists in the performance. Prototype Manager – implemented usually as a hashtable keeping the object to clone. When use it, prototype become a factory method which uses cloning instead of instantiation.

Implementing the Clone operation
A small discussion appears when talking about how deep or shallow a clone should be: a deep clone clones the instance variables in the cloning object while a shallow clone shares the instance variables between the clone and the original. Usually, a shallow clone is enough and very simple, but cloning complex prototypes should use deep clones so the clone and the original are independent, a deep clone needing its components to be the clones of the complex object’s components. When we clone complex objects which contains other objects, we should take care how they are cloned. We can clone contained objects also (deep cloning) or we can the same reference for them, and to share them between cloned container objects.

Initializing clones
There are cases when the internal states of a clone should be initialized after it is created. This happens because these values cannot be passed to the Clone() method, that uses an interface which would be destroyed if such parameters were used. In this case the initialization should be done by using setting and resetting operations of the prototype class or by using an initializing method that takes as parameters the values at which the clone’s internal states should be set.


Applicability
  • Prototypes are useful when object initialization is expensive, and you anticipate few variations on the initialization parameters. In this context, Prototype can avoid expensive “creation from scratch”, and support cheap cloning of a pre-initialized prototype.
  • Use Prototype Pattern when a system should be independent of how its products are created, composed, and represented, and:
    • Classes to be instantiated are specified at run-time
    • Avoiding the creation of a factory hierarchy is needed
    • It is more convenient to copy an existing instance than to create a new one.
    • Objects are required that are similar to existing objects.

Consequences
  • Prototype co-opts one instance of a class for use as a breeder of all future instances.
  • Prototype is unique among the other creational patterns in that it does not require a class – only an object. Object-oriented languages like Self and Omega that do away with classes completely rely on prototypes for creating new objects.
  • It allows an object to create customized objects without knowing their class or any details of how to create them.

Downsides
  • The process of copying an object can be complicated.
  • Classes that have circular references to other classes are difficult to clone.
  • Overuse of the pattern could affect performance, as the prototype object itself would need to be instantiated if you use a registry of prototypes. 

Sample Code


Related Patterns
  • Abstract Factory might store a set of Prototypes from which to clone and return product objects. Abstract Factory classes are often implemented with Factory Methods, but they can be implemented using Prototype.
  • Factory Method creation is through inheritance but Protoype creation is through delegation. Prototype does not require subclassing, but it does require an “initialize” operation. Factory Method requires subclassing, but does not require Initialize.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Protoype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
  • Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as well.

References
http://www.dofactory.com/Patterns/PatternPrototype.aspx
http://sourcemaking.com/design_patterns/prototype
http://www.oodesign.com/prototype-pattern.html
http://dotnet.dzone.com/articles/design-patterns-c-prototype
http://www.dotnetlead.com/design-patterns/prototype

Further readings
http://en.wikipedia.org/wiki/Prototype_pattern
http://ayende.com/blog/159393/design-patterns-in-the-test-of-time-prototype
http://www.codeproject.com/Articles/42582/Prototype-Design-Pattern

Friday, November 23, 2012

Singleton Design Pattern

Although they are lots of books and articles about Design Patterns, yet I like to share my point of view about common design patterns with you, and would be happy to have your thoughts or questions on comments. This post introduces GoF Singleton design pattern.

Definition
Ensure a class has only one instance and provide a global point of access to it.  (dofactory)


  • Singleton defines an Instance operation that lets clients access its unique instance. Instance is a class operation and responsible for creating and maintaining its own unique instance.

Applicability
  • When you need to ensure there is one instance of an object, available to a number of other classes, you may want to use the Singleton pattern. Singletons are used a lot where you need to provide a registry, or something like a thread pool. Logging is also another popular use of Singletons, providing one single access point to an applications log file.
  • Singleton should be considered only if all three of the following criteria are satisfied:
    • Ownership of the single instance cannot be reasonably assigned
    • Lazy initialization is desirable
    • Global access is not otherwise provided for

Consequences
  • Encapsulated “just-in-time initialization” or “initialization on first use”.
  • Ensure a class has only one instance, and provide a global point of access to it.
  • The advantage of Singleton over global variables is that you are absolutely sure of the number of instances when you use Singleton, and, you can change your mind and manage any number of instances.
  • A special care should be taken when singleton has to be used in a multithreading application.

Downsides
  • Using global state are very difficult to test.
  • Programs that rely on global state hide their dependencies.
  • Singleton user and the singleton become inextricably coupled together.
  • The Singleton design pattern is one of the most inappropriately used patterns. Singletons are intended to be used when a class must have exactly one instance, no more, no less. Designers frequently use Singletons in a misguided attempt to replace global variables. A Singleton is, for intents and purposes, a global variable. The Singleton does not do away with the global; it merely renames it.
  •  Singleton is infamous in object oriented systems. A lot of the time the Singleton is used as a shortcut, so that the designer doesn't need to think properly about object visibility. If you're hacking in a Singleton so that there is global access to a resource, maybe it's not the right thing to do. It might be better to work out how to pass the reference to that resource around properly.
  • Another important consideration is multi-threading. If two threads call the Instance() method at the same time, you can end up with two singletons. Making the Instance() method synchronized solves this issue, but then you have the performance cost - calling a synchronized version of Instance() will be slower than the non-synchronized version.  However, maybe the best way around this is to sacrifice lazy-loading in the Singleton, ensuring there can only ever be on instance.  
  • When is Singleton unnecessary? Short answer: most of the time. Long answer: when it’s simpler to pass an object resource as a reference to the objects that need it, rather than letting objects access the resource globally. The real problem with Singletons is that they give you such a good excuse not to think carefully about the appropriate visibility of an object. Finding the right balance of exposure and protection for an object is critical for maintaining flexibility.

Sample Code
Singleton pattern using double-checked locking example


Singleton pattern using .NET Lazy<T> example


Related Patterns
  • Abstract Factory, Builder, and Prototype can use Singleton in their implementation.
  • Facade objects are often Singletons because only one Facade object is required.
  • State objects are often Singletons.

Proxy Design Pattern

Although they are lots of books and articles about Design Patterns, yet I like to share my point of view about common design patterns with you, and would be happy to have your thoughts or questions on comments. This post introduces GoF Proxy design pattern.

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


  • Proxy  maintains a reference that lets the proxy access the real subject. Proxy may refer to a Subject if the RealSubject and Subject interfaces are the same. It provides an interface identical to Subject's so that a proxy can be substituted for for the real subject and controls access to the real subject and may be responsible for creating and deleting it. Other responsibilites depend on the kind of proxy:
    • Remote proxies are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.
    • Virtual proxies may cache additional information about the real subject so that they can postpone accessing it. For example, the ImageProxy from the Motivation caches the real images's extent.
    • Protection proxies check that the caller has the access permissions required to perform a request.
  • Subject  defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.
  • RealSubject defines the real object that the proxy represents.




Applicability

There are four common situations in which the Proxy pattern is applicable.
  • 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.
  • 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.
  • 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.
  • 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),
    • Loading a persistent object into memory when it’s first referenced,
    • Checking that the real object is locked before it is accessed to ensure that no other object can change it.
  • A Cache Proxy improves the performance of the underlying object's members when they perform long-running tasks that return seldom-changing results. For example, the underlying object may provide a method that calculates prime numbers. When the first call to the proxy's matching method is made, the call is passed to the real object. The results from the call are stored within the proxy object and returned to the client. For subsequent calls, the cached information in the proxy can be returned without recalculating the prime numbers.
  • DynamicProxy generates proxies for objects that can be used to transparently add or alter behavior to them, provide pre/post processing and many other things. The dynamic proxy provides one interceptor handler for all methods, and you can have many interceptors on one class.
    • Castle DynamicProxy is a library for generating lightweight .NET proxies on the fly at runtime. Proxy objects allow calls to members of an object to be intercepted without modifying the code of the class.
  • TransparentProxy is a run-time generated proxy like dynamic proxy 
    • WCF dynamic proxy is named TransparentProxy

This pattern is recommended when either of the following scenarios occur in your application:
  • The object being represented is external to the system.
  • Objects need to be created on demand. 
  • Access control for the original object is required
  • Added functionality is required when an object is accessed.

Typically, you'll want to use a proxy when communication with a third party is an expensive operation, perhaps over a network. The proxy would allow you to hold your data until you are ready to commit, and can limit the amount of times that the communication is called. In java RMI an object on one machine (executing in one JVM) called a client can invoke methods on an object in another machine (another JVM) the second object is called a remote object. The proxy (also called a stub) resides on the client machine and the client invokes the proxy in as if it is invoking the object itself (remember that the proxy implements the same interface that RealSubject implements). The proxy itself will handle communication to the remote object, invoke the method on that remote object, and would return the result if any to the client. The proxy in this case is a Remote proxy.

The proxy is also useful if you want to decouple actual implementation code from the access to a particular library. Proxy is also useful for access to large files, or graphics. By using a proxy, you can delay loading the resource until you really need the data inside. Without the concept of proxies, an application could be slow, and appear non-responsive.

Consequences
  • 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.

Downsides
  • Less efficiency due to indirection.

Sample Code
Virtual proxy example


Remote proxy example


Protective proxy example


Smart proxy example
Server

Client 

Castle DynamicProxy example

Related Patterns
  • Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface.
  • 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.

References
http://www.dofactory.com/Patterns/PatternProxy.aspx
http://sourcemaking.com/design_patterns/proxy
http://www.oodesign.com/proxy-pattern.html
http://java.dzone.com/articles/design-patterns-proxy
http://www.blackwasp.co.uk/Proxy.aspx
http://www.dotnetperls.com/protection-proxy
http://docs.castleproject.org/Tools.DynamicProxy-Introduction.ashx

Further readings
http://en.wikipedia.org/wiki/Proxy_pattern
http://en.wikipedia.org/wiki/Lazy_initialization
http://en.wikipedia.org/wiki/Lazy_loading
http://en.wikipedia.org/wiki/Lazy_evaluation
http://javapapers.com/design-patterns/proxy-design-pattern/
http://kozmic.pl/dynamic-proxy-tutorial/
http://geekswithblogs.net/abhijeetp/archive/2010/04/04/a-simple-dynamic-proxy.aspx

Tuesday, November 20, 2012

ObjectPool Design Pattern

Although they are lots of books and articles about Design Patterns, yet I like to share my point of view about common design patterns with you, and would be happy to have your thoughts or questions on comments. This post introduces Object Pool design pattern.

Definition
ObjectPool pattern is used for sharing and reusing the resources  that are expensive to create.



  • Reusable wraps the limited resource, will be shared by several clients for a limited amount of time.
  • ReusablePool manages the reusable objects for use by Clients, creating and managing a pool of objects.
  • Client  uses an instance of type Reusable.

When a client asks for a Reusable object, the pool performs the following actions:
  • Search for an available Reusable object and if it was found it will be returned to the client.
  • If no Reusable object was found then it tries to create a new one. If this actions succeeds the new Reusable object will be returned to the client.
  • If the pool was unable to create a new Reusable, the pool will wait until a reusable object will be released
However, we don’t want a process to have to wait for a particular object to be released, so the Object Pool also instantiates new objects as they are required, but must also implement a facility to clean up unused objects periodically.

Applicability
  • ObjectPool is used whenever there are several clients who needs the same stateless resource which is expensive to create.
  • ObjectPool is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low.

Consequences
  • Object pooling can offer a significant performance boost

Downsides
  • The objects should be released by the client when it finishes using them. There are plenty of examples when the client ”forget” to release the resources.
  • In order to work in a multithreading environment the methods that are used by differnt threads should be synchronized. 

Sample Code


Related Patterns
  • Although  ObjectPool and Flyweight patterns have similarity, but they have the following differences:
    • Although the object pool is handling the object instantiation it's main purpose is to provide a way for the clients to reuse the objects like they are new objects, without being shared and reused during they are acquired, but in Flyweight objects are shared.
    • Flyweight objects are usually immutable, whereas ObjectPool's Reusable objects are usually mutable. 
    • An object pool is usually a container for a set of domain objects while a flyweight usually is a domain object.
  • The Factory Method pattern can be used to encapsulate the creation logic for objects. However, it does not manage them after their creation, the object pool pattern keeps track of the objects it creates. 
  • Object Pools are usually implemented as Singletons.

Monday, November 19, 2012

Flyweight Design Pattern

Although they are lots of books and articles about Design Patterns, yet I like to share my point of view about common design patterns with you, and would be happy to have your thoughts or questions on comments. This post introduces GoF Flyweight design pattern.

Definition
Use sharing to support large numbers of fine-grained objects efficiently.  (dofactory)


  • Flyweight declares an interface through which flyweights can receive and act on extrinsic state.
  • ConcreteFlyweight implements the Flyweight interface and adds storage for intrinsic state, if any. A ConcreteFlyweight object must be sharable. Any state it stores must be intrinsic, that is, it must be independent of the ConcreteFlyweight object's context.
  • UnsharedConcreteFlyweight not all Flyweight subclasses need to be shared. The Flyweight interface enables sharing, but it doesn't enforce it. It is common for UnsharedConcreteFlyweight objects to have ConcreteFlyweight objects as children at some level in the flyweight object structure (as the Row and Column classes have).
  • FlyweightFactory creates and manages flyweight objects and ensures that flyweight are shared properly. When a client requests a flyweight, the FlyweightFactory objects assets an existing instance or creates one, if none exists.
  • Client maintains a reference to flyweight(s) and computes or stores the extrinsic state of flyweight(s).


Each “flyweight” object is divided into two pieces: the state-dependent (extrinsic) part, and the state-independent (intrinsic) part. Intrinsic state is stored (shared) in the Flyweight object. Extrinsic state is stored or computed by client objects, and passed to the Flyweight when its operations are invoked.

Applicability
  • The flyweight pattern applies to a program using a huge number of objects that have part of their internal state in common where the other part of state can vary. The pattern is used when the larger part of the object's state can be made extrinsic (external to that object).
  • The Motif GUI strategy of replacing heavy-weight widgets with light-weight gadgets.
  • The classic example of the Flyweight pattern is the representation of a character in a word processor. Rather than each character having seperate glyph objects that represent the font and formatting data, each character could have a reference to a flyweight glyph object shared by every instance of the same cahracter in the document. In this case, the character need only store it's position in the the document, rather than it's entire formatting information.

Consequences
  • Use sharing to support large numbers of fine-grained objects efficiently.
  • Flyweight pattern saves memory by sharing flyweight objects among clients. The amount of memory saved generally depends on the number of flyweight categories saved

Downsides
  • One of the drawbacks of this pattern is that all instances of the class are related, so single instance of the class will not be able to behave independently from other instances.

Sample Code


Sample Output:


Related Patterns
  • Whereas Flyweight shows how to make lots of little objects, Facade shows how to make a single object represent an entire subsystem.
  • Flyweight is often combined with Composite to implement shared leaf nodes.
  • Terminal symbols within Interpreter’s abstract syntax tree can be shared with Flyweight.
  • Flyweight explains when and how State objects can be shared.
  • Flyweights are usually created using a Factory and the Singleton is applied to that factory so that for each type or category of flyweights a single instance is returned.
  •  State and Strategy objects are usually implemented as Flyweights.

References
http://www.dofactory.com/Patterns/PatternFlyweight.aspx
http://sourcemaking.com/design_patterns/flyweight
http://www.oodesign.com/flyweight-pattern.html
http://java.dzone.com/articles/design-patterns-flyweight

Further readings
http://en.wikipedia.org/wiki/Flyweight_pattern
http://en.wikipedia.org/wiki/Flyweight
http://ayende.com/blog/159713/design-patterns-in-the-test-of-time-flyweight
http://javapapers.com/design-patterns/flyweight-design-pattern/
http://www.blackwasp.co.uk/Flyweight.aspx
http://www.avajava.com/tutorials/lessons/flyweight-pattern.html
http://www.as3dp.com/2007/11/the-flyweight-design-pattern-where-shared-objects-solve-storage-problems/

Sunday, November 18, 2012

Facade Design Pattern

Although they are lots of books and articles about Design Patterns, yet I like to share my point of view about common design patterns with you, and would be happy to have your thoughts or questions on comments. This post introduces GoF Facade design pattern.

Definition
Provide a unified interface to a set of interfaces in a subsystem. Fa├žade defines a higher-level interface that makes the subsystem easier to use. (dofactory)


  • Facade knows which subsystem classes are responsible for a request and delegates client requests to appropriate subsystem objects.
  • Subsystem classes implement subsystem functionality, handle work assigned by the Facade object and have no knowledge of the facade and keep no reference to it.



Applicability
  • A system has several identifiable subsystems and It is required to hide complexity and providing a simple API to client.
  • As the concept behind facade is to simplify an interface, service oriented architectures make use of the facade pattern.

Consequences
  • Wrap a complicated subsystem with a simpler interface.
  • Make a software library easier to use, understand and test, since the facade has convenient methods for common tasks and make the library more readable, for the same reason;
  • Reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
  • Wrap a poorly designed collection of APIs with a single well-designed API (as per task needs).

Downsides
  • By introducing the Facade into your code, you will be hardwiring subsystems into the Facade. This is fine if the subsystem never changes, but if it does, your Facade could be broken. Therefore, developers working on the subsystem should be made aware of any Facade around their code.
  • The Facade object should be a fairly simple advocate or facilitator. It should not become an all-knowing oracle or “god” object.

Sample Code

Related Patterns
  • Facade defines a new interface, whereas Adapter uses an old interface. Remember that Adapter makes two existing interfaces work together as opposed to defining an entirely new one. Adapter and Facade are both wrappers; but they are different kinds of wrappers. The intent of Facade is to produce a simpler interface, and the intent of Adapter is to design to an existing interface. While Facade routinely wraps multiple objects and Adapter wraps a single object; Facade could front-end a single complex object and Adapter could wrap several legacy objects.
  • Whereas Flyweight shows how to make lots of little objects, Facade shows how to make a single object represent an entire subsystem.
  • Mediator is similar to Facade in that it abstracts functionality of existing classes. Mediator abstracts/centralizes arbitrary communications between colleague objects. It routinely “adds value”, and it is known/referenced by the colleague objects. In contrast, Facade defines a simpler interface to a subsystem, it does not add new functionality, and it is not known by the subsystem classes.
  • Abstract Factory can be used as an alternative to Facade to hide platform-specific classes.
  • Facade objects are often Singletons because only one Facade object is required.

References
http://www.dofactory.com/Patterns/PatternFacade.aspx
http://en.wikipedia.org/wiki/Facade_pattern
http://sourcemaking.com/design_patterns/facade
http://java.dzone.com/articles/design-patterns-uncovered-1

Further readings
http://ayende.com/blog/159681/design-patterns-in-the-test-of-time-faccedil-ade
http://javapapers.com/design-patterns/facade-design-pattern/
http://blog.apigee.com/detail/api_facade_design_pattern_overview

Composite Design Pattern

Although they are lots of books and articles about Design Patterns, yet I like to share my point of view about common design patterns with you, and would be happy to have your thoughts or questions on comments. This post introduces GoF Composite design pattern.

Definition
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. (dofactory)


  • Component  declares the interface for objects in the composition and implements default behavior for the interface common to all classes, as appropriate. It declares an interface for accessing and managing its child components and optionally defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate.
  • Leaf represents leaf objects in the composition. A leaf has no children and defines behavior for primitive objects in the composition.
  • Composite  defines behavior for components having children. it stores child components and implements child-related operations in the Component interface.
  • Client manipulates objects in the composition through the Component interface.

Composite does not force you to treat all Components as Composites. It merely tells you to put all operations that you want to treat “uniformly” in the Component class. If add, remove, and similar operations cannot, or must not, be treated uniformly, then do not put them in the Component base class. Remember, by the way, that each pattern’s structure diagram does not define the pattern; it merely depicts what in our experience is a common realization thereof. Just because Composite’s structure diagram shows child management operations in the Component base class does not mean all implementations of the pattern must do the same. Visitor pattern can be used to overcome this issue, so enumeration is not a problem - the Visitor knows in each case, exactly what kind of object it’s dealing with. The Visitor doesn’t need every object to provide an enumeration interface.

Applicability
  • The composite pattern applies when there is a part-whole hierarchy of objects and a client needs to deal with objects uniformly regardless of the fact that an object might be a leaf or a branch. 
  • Graphics Editors use composite pattern to implement complex and simple graphics.
  • File System implementations use the composite design pattern (Note that a folder object usually contains one or more file or folder objects and thus is a complex object where a file is a simple object).

Consequences
  • Recursive composition
  • Composite lets clients treat individual objects and compositions of objects uniformly.

Downsides
  • The Composite pattern does one thing really well, and that is that it allows you to treat both nodes and leafs in the same way. However, by providing this flexibility and transparency, you're choosing a trade-off on the Single Responsibility principle.  This is not necessarily a bad thing, but it's something that you should keep in mind. 
  • The pattern probably is not ideal to use as a data structure. In cases where the ordering of child nodes is important, you will need to add in extra functionality, perhaps utilizing the Iterator pattern.

Sample Code

Related Patterns
  • Composite and Decorator have similar structure diagrams, reflecting the fact that both rely on recursive composition to organize an open-ended number of objects.
  • Composite can be traversed with Iterator. Visitor can apply an operation over a Composite. Composite could use Chain of Responsibility to let components access global properties through their parent. It could also use Decorator to override these properties on parts of the composition. It could use Observer to tie one object structure to another and State to let a component change its behavior as its state changes.
  • Composite can let you compose a Mediator out of smaller pieces through recursive composition.
  • Decorator is designed to let you add responsibilities to objects without subclassing. Composite’s focus is not on embellishment but on representation. These intents are distinct but complementary. Consequently, Composite and Decorator are often used in concert.
  • Flyweight is often combined with Composite to implement shared leaf nodes.

References
http://www.dofactory.com/Patterns/PatternComposite.aspx
http://sourcemaking.com/design_patterns/composite
http://www.oodesign.com/composite-pattern.html
http://java.dzone.com/articles/design-patterns-composite

Further readings
http://en.wikipedia.org/wiki/Composite_pattern
http://en.wikipedia.org/wiki/Mixin
http://ayende.com/blog/159523/design-patterns-in-the-test-of-time-composite
http://www.blackwasp.co.uk/Composite.aspx
http://www.codeproject.com/Articles/185797/Composite-Design-Pattern
http://gamedev.tutsplus.com/tutorials/implementation/using-the-composite-design-pattern-for-an-rpg-attributes-system/

Saturday, November 17, 2012

Bridge Design Pattern

Although they are lots of books and articles about Design Patterns, yet I like to share my point of view about common design patterns with you, and would be happy to have your thoughts or questions on comments. This post introduces GoF Bridge design pattern.

Definition
Decouple an abstraction from its implementation so that the two can vary independently. (dofactory)


  • Abstraction defines the abstraction's interface and maintains a reference to an object of type Implementor.
  • RefinedAbstraction extends the interface defined by Abstraction.
  • Implementor defines the interface for implementation classes. This interface doesn't have to correspond exactly to Abstraction's interface; in fact the two interfaces can be quite different. Typically the Implementation interface provides only primitive operations, and Abstraction defines higher-level operations based on these primitives.
  • ConcreteImplementor implements the Implementor interface and defines its concrete implementation.

Applicability
  • The bridge pattern applies when there is a need to avoid permanent binding between an abstraction and an implementation and when the abstraction and implementation need to vary independently. Using the bridge pattern would leave the client code unchanged with no need to recompile the code.
  • Graphical User Interface Frameworks and Persistence Frameworks  use the bridge pattern to separate abstractions from platform specific implementation. For example GUI frameworks separate a Window abstraction from a Window implementation for Linux or Mac OS using the bridge pattern.

Consequences
  • Abstraction and Implementor hierarchies can be extended independently.
  • Beyond encapsulation, to insulation
  • Run-time binding of the implementation
  • Share an implementation among multiple objects
  • Hiding details from clients
  • Reduction in the number of sub classes - Sometimes, using pure inheritance will increase the number of sub classes and using Bridge Pattern reduces the sub class requirement.
  • Improved extensibility: the extensibility is improved because additional refined abstractions can be created without the need for adding any additional implementations. Likewise, extra concrete implementations can be developed which can be used transparently with the existing and future abstractions.

Downsides
  • In providing flexibility, it increases complexity. 
  • Double indirection: The abstraction needs to pass messages along to the implementator for the operation to get executed. So, There are possible performance issues with the indirection of messages

Sample Code
Using bridge pattern as an abstraction for different persistences and repository example



Related Patterns
  • Adapter makes things work after they are designed; Bridge makes them work before they are. Bridge is designed up-front to let the abstraction and the implementation vary independently. Adapter is retrofitted to make unrelated classes work together.
  • State, Strategy, Bridge (and to some degree Adapter) have similar solution structures. They all share elements of the “handle/body” idiom. They differ in intent - that is, they solve different problems.
  • The structure of State and Bridge are identical (except that Bridge admits hierarchies of envelope classes, whereas State allows only one). The two patterns use the same structure to solve different problems: State allows an object’s behavior to change along with its state, while Bridge’s intent is to decouple an abstraction from its implementation so that the two can vary independently.
  • The Bridge pattern is a composite of the Template Method and Strategy patterns.
  • If interface classes delegate the creation of their implementation classes (instead of creating/coupling themselves directly), then the design usually uses the Abstract Factory pattern to create the implementation objects.

References
http://www.dofactory.com/Patterns/PatternBridge.aspx
http://sourcemaking.com/design_patterns/bridge
http://www.oodesign.com/bridge-pattern.html
http://java.dzone.com/articles/design-patterns-bridge
http://thecafetechno.com/tutorials/design-patterns/bridge-pattern-in-java-with-sample-code-to-download/

Further readings
http://en.wikipedia.org/wiki/Bridge_pattern
http://www.blackwasp.co.uk/Bridge.aspx
http://www.avajava.com/tutorials/lessons/bridge-pattern.html
http://today.java.net/pub/a/today/2004/10/29/patterns.html
http://www.andypatterns.com/index.php/blog/from_strategy_to_bridge/