CSC/ECE 517 Fall 2012/ch2b 2w39 ka: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
 
(84 intermediate revisions by 2 users not shown)
Line 1: Line 1:
==Introduction==
==Introduction==
Describe what Design pattern is and what are we going to discuss in this article.
In this section we will be discussing about the decorator pattern and its related patterns such as adapter pattern,proxy pattern and composite pattern.
 
==Decorator Pattern==
Explanation of Decorator pattern
===Example of its Usage//change the title===


===Decorator Pattern===
An object's state can be changed at compile time and not at run time. The change of state can be accomplished at compile time by using inheritance, however we might want to change the state of the object at run time. This can be achieved by decorator pattern.
We have an instance, and we put another instance inside of it. They both support the same (or similar) interfaces. The one on the outside is a "decorator." We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. <ref>[http://www.oodesign.com/decorator-pattern.html<i>Decorator Pattern</i>]</ref>
===Intent===
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. <ref>[http://c2.com/cgi/wiki?GangOfFour<i>"Gang of four"</i>]</ref>
===Problem===
The state of an object can be changed at compile time but no change is possible at run time if the language does not permit so.
===Solution===
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator
to extend the functionality of the objects at run time.
===Implementation===
===Implementation===


====Ruby====
====Ruby====
brief explanation and Sample Code:
The example shows a Coffee class with a method cost defining its cost as 2.
<ref>[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html<i>Decorator Pattern and more</i>]</ref>
<pre>
<pre>
    type the code here
 
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method.
 
class Coffee
  def cost
    2
  end
end
 
But what if we want the cost of a coffee with milk? We could have a new class:
 
class MilkCoffee
  def cost
    2.4
  end
end
 
But now if we want cream. And sprinkles. Clearly, creating new classes is going to lead to a huge number of classes in our application. It just isn’t realistic to create classes for different combinations of coffee and extras. It could get worse – what if we have different types of coffee? We would then have to have combinations of extras with each different type of coffee.Hence we will use decorator pattern.
 
module Decorator
  def initialize(decorated)
    @decorated = decorated
  end
 
  def method_missing(method, *args)
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)
  end
end
 
And thats all you need. You can include this into any class you want to act as a decorator. You can then use that decorator as if it was the object it is decorating; by default all messages sent to the decorator are forwarded on to the decorated object. You can then decorate the methods you need to extend:
 
class Milk
  include Decorator
 
  def cost
    @decorated.cost + 0.4
  end
end
 
So how does this solve our original problem? The real power of decorators lies in the fact that they can act like the objects they are decorating. By taking this one step further, you can wrap decorators with other decorators as long as they share the same interface. By creating decorators for our different “extras”, we can create coffees using a combination of decorators and get the total cost of the coffee.
 
class Whip
  include Decorator
 
  def cost
    @decorated.cost + 0.2
  end
end
 
class Sprinkles
  include Decorator
 
  def cost
    @decorated.cost + 0.3
  end
end
 
Whip.new(Coffee.new).cost
#=> 2.2
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost
#=> 2.9
 
</pre>
</pre>


====Java====
====Java====
brief explanation and Sample Code:  
In this java example  <ref>[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html<i>Implementing Decorator Pattern</i>]</ref>
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.
    Basic: Defines an object to which additional responsibilities can be attached.
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.
    ConcreteDecorator: adds responsibilities to the component.
<pre>
<pre>
    type the code here
</pre>
====Disadvantages====


Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.
    public interface basicInterface {
    public void do();
    }
 
    public class Basic implements basicInterface{
    public void do() {
    System.out.println("Do basic stuff");
    }
    }
 
    public interface Decorator extends basicInterface {
    public void addedStuff();
    }


*<b>Performance Overhead</b>
    public class ConcreteDecorator implements Decorator {
Because reflection involves types that are dynamically resolved, certain [http://en.wikipedia.org/wiki/Java_performance#Virtual_machine_optimization_techniques Java virtual machine optimizations] can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.


*<b>Security Restrictions</b>
    basicInterface basic;
Reflection requires a run-time permission which may not be present when running under a [http://en.wikipedia.org/wiki/Information_security_management security manager]. This is in an important consideration for code which has to run in a restricted security context, such as in an [http://en.wikipedia.org/wiki/Applet Applet].


*<b>Exposure of Internals</b>
    public ConcreteDecorator(basicInterface basic) {
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy [http://en.wikipedia.org/wiki/Software_portability portability]. Reflective code, breaks [http://en.wikipedia.org/wiki/Data_abstraction abstractions] and therefore may change behavior with upgrades of the [http://en.wikipedia.org/wiki/Computing_platform platform] <ref>[http://docs.oracle.com/javase/tutorial/reflect/index.html Disadvantages of Java Reflection API]</ref>
    super();
    this.basic = basic;
    }


===C#===
    public void addedStuff() {
    System.out.println("Decorator does other stuff too");


====Key Features====
    }
It enables you to do simple things like:
Check the type of an object at runtime (simple calls to typeof() for example)
Inspect the Attributes of an object at runtime to change the behavior of a method (the various serialization methods in .NET)
To much more complicated tasks like:
Loading an assembly at runtime, finding a specific class, determining if it matches a given Interface, and invoking certain members dynamically.
====Advantages====
*<b>Signature Based Polymorphism</b>
[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C#] programmers are familiar with [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] based on interface inheritance. Reflection provides an alternative where we can invoke methods having same [http://en.wikipedia.org/wiki/Type_signature signature], from different classes not having a common interface.


*<b>Inspecting and Manipulating Classes</b>
    public void do() {
If we need to write code that depends on class details known only at run time, then reflection comes as an easy way to proceed.
    basic.do();
    addedStuff();
    }
    }


*<b>Creating Adaptable and Flexible Solutions</b>
    public class Client {
It is possible to write code for [http://en.wikipedia.org/wiki/Factory_method_pattern factory design pattern] by loading classes using reflection instead of writing fixed code depending on specific static types with if-else statements inside the factory method.  
    public static void main(String[] args) {
    basicInterface comp = new Basic();
    Decorator decorator = new ConcreteDecorator(comp);
    decorator.do();
    }
    }


<b>Example:</b>
</pre>
To write a C# .Net program which uses reflection, the program should use the [http://en.wikipedia.org/wiki/Namespace namespace] System.Reflection.
To get type of the object, the typeof operator can be used. There is one more method GetType() which also can be used for retrieving the type information of a class. The Operator "typeof" allows us to get class name of our object and GetType() method is used to get data about object's type. Suppose we have following class:


<pre>
In this way we can add concrete decorator classes to provided the added functionality to the basic class.
    public class TestDataType
    {
        public TestDataType()
        {
          counter = 1;
        }


        public TestDataType(int c)
==Adapter Pattern==
        {
Adapter pattern acts as a bridge between objects. It adapts to the changing needs of the classes using interface. In real world we have adapters for power supplies, adapters for camera memory cards etc.If a class is expecting some type of object and we have an object offering the same features, but exposing a different interface we want to use both of them so instead of implementing them again and changing existing classes,we can create an adapter.
          counter = c;
===Intent===
        }
Match an existing object to a particular interface.
===Problem===
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a
derivative of an abstract class you already have or are defining.
===Solution===
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired
interface
===Implementation===


        private int counter;


        public int Inc()
====Ruby====
        {
The Adapter offers exactly the same interface as the adaptee, but it can override any method or add new ones. In the below code the
          return counter++;
adapter code delegates the call to the adaptee and performs operations according to the client requirements by performing additional operation to the results returned by the adaptee.
        }
features
        public int Dec()
<ref>[http://www.scribd.com/doc/396559/gof-patterns-in-ruby<i>Gof Adapter Pattern</i>]</ref>
        {
<pre>
          return counter--;
class Adaptee
        }
def talk
puts "I'm Adaptee"
end
def whine
puts "Stop bullying me!"
end
end


    }
class Adapter
def initialize
@adaptee=Adaptee.new
end
def talk
#override
puts "Let me introduce you to Adaptee!"
@adaptee.talk
puts "That was my adaptee"
end
def do_other_stuff
puts "I'm versatile"
end
def method_missing method
if
@adaptee.respond_to? method@adaptee.sendmethod
else
raise NotImplementedError,"This method is not "+\ "available on this interface"
end
end
end
if__FILE__==$0
adapter=Adapter.new
adapter.talk
adapter.whine
adapter.do_other_stuff
end
</pre>
</pre>
 
At first we should get type of object that was created. The following C# .Net code snippet shows how to do it <ref>[http://www.codersource.net/microsoft-net/c-basics-tutorials/c-net-tutorial-reflection.aspx C# Reflection]</ref>
output -
Let me introduce you to Adaptee!
I'm Adaptee
That was my adaptee
Stop bullying me!
I'm versatile
 
====Java====
The following example shows a simple implementation of the pattern. Consider that we have a third party library that provides sorting functionality through it's NumberSorter class.This is our adaptee, a third party implementation of a number sorter that deals with Lists, not arrays.[http://java.dzone.com/articles/design-patterns-uncovered-0]
<pre>
  public class NumberSorter
  {
  public List<Integer> sort(List<Integer> numbers)
  {
  //sort and return
  return new ArrayList<Integer>();
  }
  }
</pre>
 
Our Client deals with primitive arrays rather than Lists. For the sake of this example, lets say we can't change the client to use Lists.
<pre>
<pre>
TestDataType testObject = new TestDataType(15);
int[] numbers = new int[]{34, 2, 4, 12, 1};
Type objectType = testObject.GetType();
Sorter sorter = new SortListAdapter();
sorter.sort(numbers);
</pre>
</pre>


Now objectType has all the required information about class TestDataType. We can check if our class is abstract or if it is a class. The System.Type contains a few properties to retrieve the type of the class: IsAbstract, IsClass. These functions return a Boolean value if the object is abstract or of class type. Also there are some methods that return information about constructors and methods that belong to the current type (class). It can be done in a way as it is done in next example:
We've provided a Sorter interface that expects the client input. This is our target.
<pre>
<pre>
Type objectType = testObject.GetType();
public interface Sorter
{
public int[] sort(int[] numbers);
}
</pre>
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter
<pre>
public class SortListAdapter implements Sorter
{
@Override
public int[] sort(int[] numbers)
{
//convert the array to a List
List<Integer> numberList = new ArrayList<Integer>();
//call the adapter
NumberSorter sorter = new NumberSorter();
numberList = sorter.sort(numberList);
 
//convert the list back to an array and return
return sortedNumbers;
}
}
</pre>
 
===Difference between Decorator Pattern and Adapter Pattern===
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate
because of incompatible interface to interact via a adapter interface.
Inheritance and composition is used to achieve this.Decorators on the other hand are not used to add different methods to all the instances instead they are used to add specific behavior to some specific instances. Though Adapters making use of composition may also be used here, but the intention is different here with what it's in case of a Adapter.
<ref>[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html<i>Structural Patterns</i>]</ref>
 
==Proxy Pattern==
Sometimes we need the ability to control the access to an [http://en.wikipedia.org/wiki/Object_(computer_science) object]. For example if we need to use only a few methods of some costly objects we'll [http://www.geom.uiuc.edu/~daeron/docs/javaguide/java/anatomy/creating.html initialize] those objects when we need them entirely. Until that point we can use some light objects exposing the same interface as the heavy objects. These light objects are called proxies and they will instantiate those heavy objects when they are really need and by then we'll use some light objects instead.
===Intent===
"Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF
 
===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.
===Solution===
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.
 
Let's take a look at the diagram definition before we go into more detail.
[[File:ProxyDesignPattern.png|none]]
 
As usual, when dealing with design patterns we code to [http://en.wikipedia.org/wiki/Interface_(computing) interfaces]. In this case, the interface that the client knows about is the Subject. Both the Proxy and RealSubject objects implement the Subject interface, but the client may not be able to access the RealSubject without going through the Proxy. It's quite common that the Proxy would handle the creation of the RealSubject object, but it will at least have a reference to it so that it can pass messages along.
 
Let's take a look at this in action with a [http://en.wikipedia.org/wiki/Sequence_diagram sequence diagram].
[[File:SequenceDiagramForProxy.png|none]]
 
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.
 
There are many different flavours of Proxy, depending on it's purpose. You may have a protection proxy, to control access rights to an object. A virtual proxy handles the case where an object might be expensive to create, and a remote proxy controls access to a remote object.


ConstructorInfo [] info = objectType.GetConstructors();
You'll have noticed that this is very similar to the Adapter pattern. However, the main difference between bot is that the adapter will expose a different interface to allow interoperability. The Proxy exposes the same interface, but gets in the way to save processing time or memory.
MethodInfo [] methods = objectType.GetMethods();


// get all the constructors
===Example===
Console.WriteLine("Constructors:");
There are four common situations in which the Proxy pattern is applicable <ref>[http://java.dzone.com/articles/design-patterns-proxy<i>Proxy Pattern</i>]</ref>
foreach( ConstructorInfo cf in info )
.
{
  Console.WriteLine(cf);
}


Console.WriteLine();
*A virtual proxy is a placeholder for “expensive to create” objects.
// get all the methods
The real object is only created when a client first requests/accesses the object. In place of a complex or heavy object use a skeleton representation. When an underlying image is huge in size, just represent it using a virtual proxy object and on demand load the real object. You feel that the real object is expensive in terms of instantiation and so without the real need we are not going to use the real object. Until the need arises we will use the virtual proxy.
Console.WriteLine("Methods:");
 
foreach( MethodInfo mf in methods )
*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. Think of an ATM implementation, it will hold proxy objects for bank information that exists in the remote server. RMI is an example of proxy implmenetation for this type in java.
  Console.WriteLine(mf);
 
}
*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. You might be well aware of the proxy server that provides you internet. Saying more than provides, the right word is censores internet. The management feels its better to censor some content and provide only work related web pages. Proxy server does that job. This is a type of proxy design pattern. Lighter part of censor is, we search for something critical in Google and click the result and you get this page is blocked by proxy server. You never know why this page is blocked and you feel this is genuine. How do you overcome that, over a period you learn to live with it.
 
*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.
 
===Implementation===
 
====Ruby====
Let’s assume you need to log all method calls made to a bank Account object without changing the original Account definition. You can create a new class to wrap the Account object, log any method call then forward the request to the target object.
Here’s a super simple bank Account.
<pre>
  class Account
 
  def initialize(amount)
    @amount = amount
  end
 
  def deposit(amount)
    @amount += amount
  end
 
  def withdraw(amount)
    @amount -= amount
  end
 
  def balance
    @amount
  end
 
  def inspect
    puts "Amount: #{@amount}"
  end
 
end
</pre>
</pre>


Now, the above program returns a list of methods and constructors of TestDataType class.
and here’s our AccountLogger class.
<pre>
class AccountLogger < BasicObject


====Disadvantages====
  def initialize(amount)
*<b>Exposes Implementation Details</b>
    @operations = []
Use of reflection exposes much of the implementation details such as the methods, fields, [http://en.wikipedia.org/wiki/Class_(computer_programming)#Member_accessibility accessibility] and other [http://en.wikipedia.org/wiki/Metadata_(CLI) metadata] of the class used.
 
    @target = Account.new(amount)
    @operations << [:initialize, [amount]]
  end
 
  def method_missing(method, *args, &block)
    @operations << [method, args]
    @target.send(method, *args, &block)
  end
 
  def operations
    @operations
  end
 
end
</pre>
The AccountLogger is our Proxy object. It doesn’t know anything about the target object, in fact it limits itself to log method calls and forward the request to the underlying @target using the method_missing hook.BasicObject actually prevents this issue by exposing a limited set of instance methods. Simply put, it copes with the problem from a different point of view: instead of taking a rich object and removing all the unnecessary methods, take a poor object and only define what you actually need.
 
====Java====
From JDK 1.3 java has direct support for implementing proxy design pattern. We need not worry on mainting the reference and object creation. Java provides us the needed utilities. Following example implementation explains on how to use java’s api for proxy design pattern.
<pre>
public interface Animal {
  public void getSound();
}
</pre>


*<b>Performance</b>
<pre>
The code that is reflective is slow than the direct code that performs the same functionality. As reflection performance also depends on the kind of operations that are done in the code like creating objects, accessing members, making method calls, etc.
public class Lion implements Animal {
  public void getSound() {
    System.out.println("Roar");
  }
}
</pre>


===Smalltalk===
Example in [http://en.wikipedia.org/wiki/Smalltalk Smalltalk]
<pre>
<pre>
w := Workspace new.
import java.lang.reflect.InvocationHandler;
w openLabel:'My Workspace'
import java.lang.reflect.Method;
w inspect
public class AnimalInvocationHandler implements InvocationHandler {
  public AnimalInvocationHandler(Object realSubject) {
    this.realSubject = realSubject;
  }
  public Object invoke(Object proxy, Method m, Object[] args) {
    Object result = null;
    try {
      result = m.invoke(realSubject, args);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return result;
  }
  private Object realSubject = null;
}
</pre>
<pre>
import java.lang.reflect.Proxy;
public class ProxyExample {
  public static void main(String[] args) {
    Animal realSubject = new Lion();
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()
        .getClassLoader(), realSubject.getClass().getInterfaces(),
        new AnimalInvocationHandler(realSubject));
    proxy.getSound();
  }
}
</pre>
</pre>
Here we can inspect all the methods available to the instance 'w'.


===PHP===
We have created a proxy handler that will be able to get the sound depending on the type of animal.
Example in [http://en.wikipedia.org/wiki/PHP PHP]<pre>
 
$reflector = new ReflectionClass("SimpleXMLElement");
===Difference between Decorator Pattern and Proxy Pattern===
echo $reflector;
The two UML diagrams may confuse us. The two design patterns looks the same with each other. With Decorator Pattern, the decorator and the decoratee implement the same interfaces. With Proxy Pattern, the proxy class and the real class delegated implement the same interfaces. Furthermore, no matter which pattern is used, it is easy to add functions before or after the method of the real object.       
However, in fact, there are some differences between Decorator Pattern and Proxy Pattern. Decorator Pattern focuses on dynamically adding functions to an object, while Proxy Pattern focuses on controlling access to an object. In other words, with Proxy Pattern, the proxy class can hide the detail information of an object from its client. Therefore, when using Proxy Pattern, we usually create an instance of object inside the proxy class. And when using Decorator Pattern, we typically pass the original object as a parameter to the constructor of the decorator.We can use another sentence to conclude thire differences:
<pre>
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively
constructed at runtime.
</pre>
</pre>
Output of this example is the complete class map of the class SimpleXMLElement.


==Comparison of Reflection in different languages==
==Composite Pattern==
When we want to represent part-whole hierarchy, use [http://en.wikipedia.org/wiki/Tree_structure tree structure] and compose objects. We know tree structure what a tree structure is and some of us don’t know what a part-whole hierarchy is. A system consists of subsystems or components. Components can further be divided into smaller components. Further smaller components can be divided into smaller elements. This is a part-whole hierarchy.
Everything around us can be a candidate for part-whole hierarchy. Human body, a car, a computer, lego structure, etc. A car is made up of engine, tyre,etc.  Engine is made up of electrical components, valves, etc. Electrical components is made up of chips, transistor,etc. Like this a component is part of a whole system. This hierarchy can be represented as a tree structure using composite design pattern. <ref>[http://www.oodesign.com/composite-pattern.html<i>Composite Pattern</i>]</ref>
===Intent===
“Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.” is the intent by GoF.
===Problem===
Application needs to manipulate a hierarchical collection of “primitive” and “composite” objects. Processing of a primitive object is handled one way, and processing of a composite object is handled differently. Having to query the “type” of each object before attempting to process it is not desirable.
===Solution===
The figure below shows a UML class diagram for the Composite Pattern:
[[File:Composite.png|none]]


{| class="wikitable" border="1"
*Component - Component is the abstraction for leafs and composites. It defines the interface that must be implemented by the objects in the composition. For example a file system resource defines move, copy, rename, and getSize methods for files and folders.
*Leaf - Leafs are objects that have no children. They implement services described by the Component interface. For example a file object implements move, copy, rename, as well as getSize methods which are related to the Component interface.
*Composite - A Composite stores child components in addition to implementing methods defined by the component interface. Composites implement methods defined in the Component interface by delegating to child components. In addition composites provide additional methods for adding, removing, as well as getting components.
*Client - The client manipulates objects in the hierarchy using the component interface.


|-
A client has a reference to a tree data structure and needs to perform operations on all nodes independent of the fact that a node might be a branch or a leaf. The client simply obtains reference to the required node using the component interface, and deals with the node using this interface; it doesn't matter if the node is a composite or a leaf.
! Java
! Ruby
! C#
! PHP
! C++


|-
===Example===
| Supports Reflection
*GUI toolkits:
| Supports Reflection
For example, Java SWT (Standard Widget Toolkit). If you want to apply a theme for a dialog, you need to apply the theme for the dialog and all its child components. A child can be a composite or a widget itself. If it is a widget, there is no child for that, and the theme needs to be applied only for the widget. But if it is a composite, we need to apply the theme for all its children. Now again, a child can be a widget or a composite. The loop continues until it covers all child widgets.
| Supports Reflection
| Supports Reflection
| Poor support for Reflection <ref>[http://grid.cs.binghamton.edu/projects/publications/c++-HPC07/c++-HPC07.pdf Tharaka Devadithya, Kenneth Chiu, Wei Lu, <i>"Reflection for High Performance Problem Solving Environments"</i>, Computer Science Department, Indiana University, 2007]</ref>


|-
*Destruction of objects in C++:
| Not Powerful and flexible as Ruby Reflection
Take any OO language without a garbage collector. Just imagine you have a data structure like tree. Each object has a reference only to his children and the client is aware of only the root node object. How will you destroy all the objects, leaving no memory leak? It is only a couple of lines of code that takes to destroy the complete code.
| Provides powerful and flexible Reflection mechanism
Kill a node = Kill all its children and then kill yourself.
| Not Powerful and flexible as Ruby
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.
| Powerful and flexible
| Provides [http://en.wikipedia.org/wiki/Run-time_type_information RTTI ] support which provides only a very      restricted subset of reflection


|-
In both the above mentioned cases using a composite pattern based recursion is a wise approach.
| Uses Reflection
| Ability to [http://en.wikipedia.org/wiki/Type_introspection introspect ] as it is a dynamic language
| Uses Reflection
| Ability to type introspect as it is a dynamic language
| C++ supports type introspection via the [http://en.wikipedia.org/wiki/Typeid typeid] and [http://en.wikipedia.org/wiki/Dynamic_cast dynamic_cast] keywords


|-
===Implementation===
| Variable's type determines its class and methods.
| Ruby supports liberated objects(cannot tell exactly what an object can do until you look under its hood)
| Variable's type determines its class and methods.
| Uses Reflection class
| It is possible to get object run-time type only if object class contains virtual functions(using RTTI)


|-
====Ruby====
| Java Reflection API (is a bit higher level than the C# Reflection API) <ref>[http://mydov.blogspot.com/2012/05/reflection-in-java-c-but-not-in-c.html Difference between Java and C# Reflection APIs]</ref>
<ref>[http://blog.rubybestpractices.com/posts/gregory/060-issue-26-structural-design-patterns.html<i>Implementation in ruby</i>]</ref>
| Ruby has a rich set of Reflection APIs
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks & SubTasks, Parts & SubParts.
| Has Reflection APIs
<pre>
| Has Reflection APIs
    class Part
| Has no Reflection APIs
  def initialize name
    @name = name
  end
  def weight
    0
  end
end


|}
class Hand < Part
  def initialize
    super("Hand")
    @children = []
    5.times {add_child Finger.new}
  end


==Applications of Reflection==
  def weight #component object
*Reflection has become invaluable to programmers who need to connect code with data. For example in a [http://en.wikipedia.org/wiki/Graphical_user_interface GUI] environment, a button might need to invoke different methods in different classes. Reflection can be used here to call the method on any given class.  
    weight &nbsp;= 5
    @children.each { |c| weight += c.weight }
    weight
  end


*Programmers who deal with a multitude of classes at the same time can use reflection to create a [http://en.wikipedia.org/wiki/Serializer serializer] that for a given class uses reflection to go through all the instance variables and processes them accordingly.
  def add_child child
    @children << child
  end
end


*Reflection is used in large test frameworks where reflection helps in identifying the [http://en.wikipedia.org/wiki/Test_method test methods] for different scenarios.
class Finger < Part
  def initialize
    super("Finger")
  end


*Reflection provides the ability to [http://en.wikipedia.org/wiki/Code_morphing morph the code] based on dynamic situations. This provides a sense of [http://en.wikipedia.org/wiki/Artificial_intelligence artificial intelligence] to the program as whole.
  def weight #Leaf object
    1
  end
end
hand = Hand.new
puts hand.weight #7
</pre>
Note here that the complex weight methods have been implemented in the component class and not the leaf class.


*Reflection can be used to debug and verify code as it provides access to the insides of a program.
====Java====
Here is the sample code that implements composite pattern.
<pre>
    public class Block implements Group {
    public void assemble() {
        System.out.println("Block");
    }
}
</pre>


*Reflection is very useful when the software is upgraded regularly. It provides an easy method to check for available methods and classes. This prevents the errors caused by the absence of methods and classes when they are deprecated.
<pre>
public interface Group {
    public void assemble();
}
</pre>


==Advantages and disadvantages of reflection==
<pre>
import java.util.ArrayList;
import java.util.List;
public class Structure implements Group {
  // Collection of child groups.
  private List<Group> groups = new ArrayList<Group>();
  public void assemble() {
    for (Group group : groups) {
      group.assemble();
    }
  }
  // Adds the group to the structure.
  public void add(Group group) {
    groups.add(group);
  }
  // Removes the group from the structure.
  public void remove(Group group) {
    groups.remove(group);
  }
}
</pre>


===Advantages===
<pre>
* <b>Extensibility:</b> Reflection provides the capability of using external and user defined classes by instantiation of extensibility objects using their fully qualified names.
public class ImplementComposite {
* <b>Class browsers in [http://en.wikipedia.org/wiki/IDE IDEs]:</b> The ability to examine the members of classes makes implementation of visual aids , [http://en.wikipedia.org/wiki/Autocomplete auto-completion] and [http://en.wikipedia.org/wiki/Software_documentation documentation] easy in development tools for programmers.
  public static void main(String[] args) {
* <b>[http://en.wikipedia.org/wiki/Debugging Debugging]:</b> Reflection allows the user to observe the private members in classes. This capability can be used to debug classes and their interactions.
          //Initialize three blocks
* <b>[http://en.wikipedia.org/wiki/Test_harness Test Harness]:</b> Reflection can be used to call a set of testing APIs defined on a class for maximum coverage of testing.
          Block block1 = new Block();
* <b>Correctness</b> : Reflection improves the robustness and the correctness of a program  especially in dynamically typed languages as run time checks can be added to check the availability of the methods or classes.
          Block block2 = new Block();
          Block block3 = new Block();
          //Initialize three structure
          Structure structure = new Structure();
          Structure structure1 = new Structure();
          Structure structure2 = new Structure();
          //Composes the groups
          structure1.add(block1);
          structure1.add(block2);
          structure2.add(block3);
          structure.add(structure1);
          structure.add(structure2);
          structure.assemble();
      }
}
</pre>


===Disadvantages===
===Difference between Decorator Pattern and Composite Pattern===
* Reflection introduces lot of performance overhead when compared to non-reflective code. Hence it should be used judiciously.
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.
* Since it provides access to the internals of a class or an encapsulated object security becomes a major issue.
The composite pattern allows you to build a hierarchical structure (such as a tree of elements) in a way that allows your external code to view the entire structure as a single entity. So the interface to a leaf entity is exactly the same as the entity for a compound entity. Essence is that all elements in your composite structure have the same interface even though some are leafs and others are entire structures. User interfaces often use this approach to allow easy composability.
* Since it is run-time binding we lose the security of compile time checks and verification <ref>[https://docs.google.com/a/ncsu.edu/viewer?a=v&q=cache:bnm9xJhl8EkJ:www.ics.uci.edu/~lopes/teaching/inf212W12/lectures/INF212-Reflection.pptx+reflection+analysis+over+ruby+java+c%23&hl=en&gl=us&pid=bl&srcid=ADGEESgNhIwaccNOPEKsCXmB8wZYIb4ZkP7HfShvDyrJOrI2z1Octe68TIM-DszvvTM5MZdFcJkT5NV5cSHrkxNICJya-VcIfqB22M2AvoBT5KmpvNV3lwUfhOgSKEGBu0gqtxJOK-aq&sig=AHIEtbTsPbOfryUJKCgMqZ6W2wbA522bCQ Analysis of Programming Languages]</ref>
However, The decorator pattern allows an entity to completely contain another entity so that using the decorator looks identical to the contained entity. This allows the decorator to modify the behavior and/or content of whatever it is encapsulating without changing the outward appearance of the entity. For example, you might use a decorator to add logging output on the usage of the contained element without changing any behavior of the contained element.


==Conclusion==
==Conclusion==
This article makes an attempt to explain the concept of Reflection in Object Oriented Programming. The article mentions the different approaches to reflection in Ruby and other languages.It mentions the usage of Reflections and the advantages and disadvantages of using Reflection. A follow up to this article would be to study the concept of [http://en.wikipedia.org/wiki/Metaprogramming Metaprogramming].
This article makes an attempt to explain the concept of Decorator Pattern and other similar patterns such as Proxy Pattern, Adapter Pattern and Composite Pattern. It also explains how each of these related patterns differ from decorator pattern.


==References==
==References==
<references />
<references />
==Additional Reading==
==Additional Reading==
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]
*[http://www.oodesign.com/composite-pattern.html Composite Pattern]
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]
*[http://javapapers.com/design-patterns/proxy-design-pattern/ Brief overview of proxy pattern]
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]
*[http://javapapers.com/design-patterns/composite-design-pattern/ Brief overview of Composite Pattern]
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]
*[http://blog.rubybestpractices.com/posts/gregory/060-issue-26-structural-design-patterns.html Patterns in Ruby]
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]
*[http://www.simonecarletti.com/blog/2010/05/understanding-ruby-and-rails-proxy-patter-delegation-and-basicobject/ Proxy pattern in Ruby]
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]
*[http://powerdream5.wordpress.com/2007/11/17/the-differences-between-decorator-pattern-and-proxy-pattern/ Differences between Proxy and Decorator pattern]
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]
*[http://java.dzone.com/articles/design-patterns-composite composite Pattern]
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]
*[http://www.codeproject.com/Articles/29036/Patterns-in-Real-Life Real life examples]
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]
*[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Composite Pattern in Ruby]
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]

Latest revision as of 03:33, 20 November 2012

Introduction

In this section we will be discussing about the decorator pattern and its related patterns such as adapter pattern,proxy pattern and composite pattern.

Decorator Pattern

An object's state can be changed at compile time and not at run time. The change of state can be accomplished at compile time by using inheritance, however we might want to change the state of the object at run time. This can be achieved by decorator pattern. We have an instance, and we put another instance inside of it. They both support the same (or similar) interfaces. The one on the outside is a "decorator." We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. <ref>Decorator Pattern</ref>

Intent

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. <ref>"Gang of four"</ref>

Problem

The state of an object can be changed at compile time but no change is possible at run time if the language does not permit so.

Solution

Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator to extend the functionality of the objects at run time.

Implementation

Ruby

The example shows a Coffee class with a method cost defining its cost as 2. <ref>Decorator Pattern and more</ref>

  
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. 

class Coffee
  def cost
    2
  end
end

But what if we want the cost of a coffee with milk? We could have a new class:

class MilkCoffee
  def cost
    2.4
  end
end

But now if we want cream. And sprinkles. Clearly, creating new classes is going to lead to a huge number of classes in our application. It just isn’t realistic to create classes for different combinations of coffee and extras. It could get worse – what if we have different types of coffee? We would then have to have combinations of extras with each different type of coffee.Hence we will use decorator pattern.

module Decorator
  def initialize(decorated)
    @decorated = decorated
  end

  def method_missing(method, *args)
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)
  end
end

And thats all you need. You can include this into any class you want to act as a decorator. You can then use that decorator as if it was the object it is decorating; by default all messages sent to the decorator are forwarded on to the decorated object. You can then decorate the methods you need to extend:

class Milk
  include Decorator

  def cost
    @decorated.cost + 0.4
  end
end

So how does this solve our original problem? The real power of decorators lies in the fact that they can act like the objects they are decorating. By taking this one step further, you can wrap decorators with other decorators as long as they share the same interface. By creating decorators for our different “extras”, we can create coffees using a combination of decorators and get the total cost of the coffee.

class Whip
  include Decorator

  def cost 
    @decorated.cost + 0.2
  end
end

class Sprinkles
  include Decorator

  def cost
    @decorated.cost + 0.3
  end
end

Whip.new(Coffee.new).cost
#=> 2.2
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost
#=> 2.9

Java

In this java example <ref>Implementing Decorator Pattern</ref>

   basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.
   Basic: Defines an object to which additional responsibilities can be attached.
   Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.
   ConcreteDecorator: adds responsibilities to the component.

    public interface basicInterface {
    public void do();
    }

    public class Basic implements basicInterface{
    public void do() {
    System.out.println("Do basic stuff");
    }
    }

    public interface Decorator extends basicInterface {
    public void addedStuff();
    }

    public class ConcreteDecorator implements Decorator {

    basicInterface basic;

    public ConcreteDecorator(basicInterface basic) {
    super();
    this.basic = basic;
    }

    public void addedStuff() {
    System.out.println("Decorator does other stuff too");

    }

    public void do() {
    basic.do();
    addedStuff();
    }
    }

    public class Client {
    public static void main(String[] args) {
    basicInterface comp = new Basic();
    Decorator decorator = new ConcreteDecorator(comp);
    decorator.do();
    }
    }

In this way we can add concrete decorator classes to provided the added functionality to the basic class.

Adapter Pattern

Adapter pattern acts as a bridge between objects. It adapts to the changing needs of the classes using interface. In real world we have adapters for power supplies, adapters for camera memory cards etc.If a class is expecting some type of object and we have an object offering the same features, but exposing a different interface we want to use both of them so instead of implementing them again and changing existing classes,we can create an adapter.

Intent

Match an existing object to a particular interface.

Problem

A system has the right data and behavior but the wrong interface. Typically used when you have to make something a derivative of an abstract class you already have or are defining.

Solution

Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired interface

Implementation

Ruby

The Adapter offers exactly the same interface as the adaptee, but it can override any method or add new ones. In the below code the adapter code delegates the call to the adaptee and performs operations according to the client requirements by performing additional operation to the results returned by the adaptee. features <ref>Gof Adapter Pattern</ref>

 
class Adaptee 
def talk 
puts "I'm Adaptee"
end
def whine
 puts "Stop bullying me!"
end
end

class Adapter
def initialize
@adaptee=Adaptee.new
end
def talk
#override
 puts "Let me introduce you to Adaptee!"
@adaptee.talk
 puts "That was my adaptee"
end
def do_other_stuff
 puts "I'm versatile"
end
def method_missing method
if
@adaptee.respond_to? method@adaptee.sendmethod
else 
raise NotImplementedError,"This method is not "+\ "available on this interface"
end
end
end
if__FILE__==$0
adapter=Adapter.new
adapter.talk
adapter.whine
adapter.do_other_stuff
end

output - Let me introduce you to Adaptee! I'm Adaptee That was my adaptee Stop bullying me! I'm versatile

Java

The following example shows a simple implementation of the pattern. Consider that we have a third party library that provides sorting functionality through it's NumberSorter class.This is our adaptee, a third party implementation of a number sorter that deals with Lists, not arrays.[1]

  public class NumberSorter
  {
  public List<Integer> sort(List<Integer> numbers)
  {
  //sort and return
  return new ArrayList<Integer>();
  }
  }

Our Client deals with primitive arrays rather than Lists. For the sake of this example, lets say we can't change the client to use Lists.

int[] numbers = new int[]{34, 2, 4, 12, 1}; 
Sorter sorter = new SortListAdapter();
sorter.sort(numbers);

We've provided a Sorter interface that expects the client input. This is our target.

public interface Sorter
{
public int[] sort(int[] numbers);
}

Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter

public class SortListAdapter implements Sorter
{
@Override
public int[] sort(int[] numbers)
{
//convert the array to a List
List<Integer> numberList = new ArrayList<Integer>();
//call the adapter
NumberSorter sorter = new NumberSorter();
numberList = sorter.sort(numberList);

//convert the list back to an array and return 
return sortedNumbers;
}
}

Difference between Decorator Pattern and Adapter Pattern

Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate because of incompatible interface to interact via a adapter interface. Inheritance and composition is used to achieve this.Decorators on the other hand are not used to add different methods to all the instances instead they are used to add specific behavior to some specific instances. Though Adapters making use of composition may also be used here, but the intention is different here with what it's in case of a Adapter. <ref>Structural Patterns</ref>

Proxy Pattern

Sometimes we need the ability to control the access to an object. For example if we need to use only a few methods of some costly objects we'll initialize those objects when we need them entirely. Until that point we can use some light objects exposing the same interface as the heavy objects. These light objects are called proxies and they will instantiate those heavy objects when they are really need and by then we'll use some light objects instead.

Intent

"Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF

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.

Solution

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.

Let's take a look at the diagram definition before we go into more detail.

As usual, when dealing with design patterns we code to interfaces. In this case, the interface that the client knows about is the Subject. Both the Proxy and RealSubject objects implement the Subject interface, but the client may not be able to access the RealSubject without going through the Proxy. It's quite common that the Proxy would handle the creation of the RealSubject object, but it will at least have a reference to it so that it can pass messages along.

Let's take a look at this in action with a sequence diagram.

As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.

There are many different flavours of Proxy, depending on it's purpose. You may have a protection proxy, to control access rights to an object. A virtual proxy handles the case where an object might be expensive to create, and a remote proxy controls access to a remote object.

You'll have noticed that this is very similar to the Adapter pattern. However, the main difference between bot is that the adapter will expose a different interface to allow interoperability. The Proxy exposes the same interface, but gets in the way to save processing time or memory.

Example

There are four common situations in which the Proxy pattern is applicable <ref>Proxy Pattern</ref> .

  • 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. In place of a complex or heavy object use a skeleton representation. When an underlying image is huge in size, just represent it using a virtual proxy object and on demand load the real object. You feel that the real object is expensive in terms of instantiation and so without the real need we are not going to use the real object. Until the need arises we will use the virtual proxy.

  • 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. Think of an ATM implementation, it will hold proxy objects for bank information that exists in the remote server. RMI is an example of proxy implmenetation for this type in java.

  • 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. You might be well aware of the proxy server that provides you internet. Saying more than provides, the right word is censores internet. The management feels its better to censor some content and provide only work related web pages. Proxy server does that job. This is a type of proxy design pattern. Lighter part of censor is, we search for something critical in Google and click the result and you get this page is blocked by proxy server. You never know why this page is blocked and you feel this is genuine. How do you overcome that, over a period you learn to live with it.

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

Implementation

Ruby

Let’s assume you need to log all method calls made to a bank Account object without changing the original Account definition. You can create a new class to wrap the Account object, log any method call then forward the request to the target object. Here’s a super simple bank Account.

   class Account

  def initialize(amount)
    @amount = amount
  end

  def deposit(amount)
    @amount += amount
  end

  def withdraw(amount)
    @amount -= amount
  end

  def balance
    @amount
  end

  def inspect
    puts "Amount: #{@amount}"
  end

end

and here’s our AccountLogger class.

class AccountLogger < BasicObject

  def initialize(amount)
    @operations = []

    @target = Account.new(amount)
    @operations << [:initialize, [amount]]
  end

  def method_missing(method, *args, &block)
    @operations << [method, args]
    @target.send(method, *args, &block)
  end

  def operations
    @operations
  end

end

The AccountLogger is our Proxy object. It doesn’t know anything about the target object, in fact it limits itself to log method calls and forward the request to the underlying @target using the method_missing hook.BasicObject actually prevents this issue by exposing a limited set of instance methods. Simply put, it copes with the problem from a different point of view: instead of taking a rich object and removing all the unnecessary methods, take a poor object and only define what you actually need.

Java

From JDK 1.3 java has direct support for implementing proxy design pattern. We need not worry on mainting the reference and object creation. Java provides us the needed utilities. Following example implementation explains on how to use java’s api for proxy design pattern.

public interface Animal {
 
   public void getSound();
 
}
public class Lion implements Animal {
 
  public void getSound() {
     System.out.println("Roar");
  }
 
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
 
public class AnimalInvocationHandler implements InvocationHandler {
  public AnimalInvocationHandler(Object realSubject) {
    this.realSubject = realSubject;
  }
 
  public Object invoke(Object proxy, Method m, Object[] args) {
    Object result = null;
    try {
      result = m.invoke(realSubject, args);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return result;
  }
 
  private Object realSubject = null;
}
import java.lang.reflect.Proxy;
 
public class ProxyExample {
 
  public static void main(String[] args) {
    Animal realSubject = new Lion();
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()
        .getClassLoader(), realSubject.getClass().getInterfaces(),
        new AnimalInvocationHandler(realSubject));
    proxy.getSound();
  }
}

We have created a proxy handler that will be able to get the sound depending on the type of animal.

Difference between Decorator Pattern and Proxy Pattern

The two UML diagrams may confuse us. The two design patterns looks the same with each other. With Decorator Pattern, the decorator and the decoratee implement the same interfaces. With Proxy Pattern, the proxy class and the real class delegated implement the same interfaces. Furthermore, no matter which pattern is used, it is easy to add functions before or after the method of the real object. However, in fact, there are some differences between Decorator Pattern and Proxy Pattern. Decorator Pattern focuses on dynamically adding functions to an object, while Proxy Pattern focuses on controlling access to an object. In other words, with Proxy Pattern, the proxy class can hide the detail information of an object from its client. Therefore, when using Proxy Pattern, we usually create an instance of object inside the proxy class. And when using Decorator Pattern, we typically pass the original object as a parameter to the constructor of the decorator.We can use another sentence to conclude thire differences:

With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively 
constructed at runtime.

Composite Pattern

When we want to represent part-whole hierarchy, use tree structure and compose objects. We know tree structure what a tree structure is and some of us don’t know what a part-whole hierarchy is. A system consists of subsystems or components. Components can further be divided into smaller components. Further smaller components can be divided into smaller elements. This is a part-whole hierarchy. Everything around us can be a candidate for part-whole hierarchy. Human body, a car, a computer, lego structure, etc. A car is made up of engine, tyre,etc. Engine is made up of electrical components, valves, etc. Electrical components is made up of chips, transistor,etc. Like this a component is part of a whole system. This hierarchy can be represented as a tree structure using composite design pattern. <ref>Composite Pattern</ref>

Intent

“Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.” is the intent by GoF.

Problem

Application needs to manipulate a hierarchical collection of “primitive” and “composite” objects. Processing of a primitive object is handled one way, and processing of a composite object is handled differently. Having to query the “type” of each object before attempting to process it is not desirable.

Solution

The figure below shows a UML class diagram for the Composite Pattern:

  • Component - Component is the abstraction for leafs and composites. It defines the interface that must be implemented by the objects in the composition. For example a file system resource defines move, copy, rename, and getSize methods for files and folders.
  • Leaf - Leafs are objects that have no children. They implement services described by the Component interface. For example a file object implements move, copy, rename, as well as getSize methods which are related to the Component interface.
  • Composite - A Composite stores child components in addition to implementing methods defined by the component interface. Composites implement methods defined in the Component interface by delegating to child components. In addition composites provide additional methods for adding, removing, as well as getting components.
  • Client - The client manipulates objects in the hierarchy using the component interface.

A client has a reference to a tree data structure and needs to perform operations on all nodes independent of the fact that a node might be a branch or a leaf. The client simply obtains reference to the required node using the component interface, and deals with the node using this interface; it doesn't matter if the node is a composite or a leaf.

Example

  • GUI toolkits:

For example, Java SWT (Standard Widget Toolkit). If you want to apply a theme for a dialog, you need to apply the theme for the dialog and all its child components. A child can be a composite or a widget itself. If it is a widget, there is no child for that, and the theme needs to be applied only for the widget. But if it is a composite, we need to apply the theme for all its children. Now again, a child can be a widget or a composite. The loop continues until it covers all child widgets.

  • Destruction of objects in C++:

Take any OO language without a garbage collector. Just imagine you have a data structure like tree. Each object has a reference only to his children and the client is aware of only the root node object. How will you destroy all the objects, leaving no memory leak? It is only a couple of lines of code that takes to destroy the complete code. Kill a node = Kill all its children and then kill yourself. Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.

In both the above mentioned cases using a composite pattern based recursion is a wise approach.

Implementation

Ruby

<ref>Implementation in ruby</ref> Use this in cases where your design seems to have a hierarchy. The hierarchy can be established by data/logic i.e Tasks & SubTasks, Parts & SubParts.

     class Part
  def initialize name
    @name = name
  end
  def weight
    0
  end
end

class Hand < Part
  def initialize
    super("Hand")
    @children = []
    5.times {add_child Finger.new}
  end

  def weight #component object
    weight  = 5
    @children.each { |c| weight += c.weight }
    weight
  end

  def add_child child
    @children << child
  end
end

class Finger < Part
  def initialize
    super("Finger")
  end

  def weight #Leaf object
    1
  end
end
hand = Hand.new
puts hand.weight #7

Note here that the complex weight methods have been implemented in the component class and not the leaf class.

Java

Here is the sample code that implements composite pattern.

    public class Block implements Group {
 
    public void assemble() {
        System.out.println("Block");
    }
}
public interface Group {
    public void assemble();
}
import java.util.ArrayList;
import java.util.List;
 
public class Structure implements Group {
  // Collection of child groups.
  private List<Group> groups = new ArrayList<Group>();
 
  public void assemble() {
    for (Group group : groups) {
      group.assemble();
    }
  }
 
  // Adds the group to the structure.
  public void add(Group group) {
    groups.add(group);
  }
 
  // Removes the group from the structure.
  public void remove(Group group) {
    groups.remove(group);
  }
}
public class ImplementComposite {
   public static void main(String[] args) {
          //Initialize three blocks
          Block block1 = new Block();
          Block block2 = new Block();
          Block block3 = new Block();
 
          //Initialize three structure
          Structure structure = new Structure();
          Structure structure1 = new Structure();
          Structure structure2 = new Structure();
 
          //Composes the groups
          structure1.add(block1);
          structure1.add(block2);
 
          structure2.add(block3);
 
          structure.add(structure1);
          structure.add(structure2);
 
          structure.assemble();
      }
}

Difference between Decorator Pattern and Composite Pattern

They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern. The composite pattern allows you to build a hierarchical structure (such as a tree of elements) in a way that allows your external code to view the entire structure as a single entity. So the interface to a leaf entity is exactly the same as the entity for a compound entity. Essence is that all elements in your composite structure have the same interface even though some are leafs and others are entire structures. User interfaces often use this approach to allow easy composability. However, The decorator pattern allows an entity to completely contain another entity so that using the decorator looks identical to the contained entity. This allows the decorator to modify the behavior and/or content of whatever it is encapsulating without changing the outward appearance of the entity. For example, you might use a decorator to add logging output on the usage of the contained element without changing any behavior of the contained element.

Conclusion

This article makes an attempt to explain the concept of Decorator Pattern and other similar patterns such as Proxy Pattern, Adapter Pattern and Composite Pattern. It also explains how each of these related patterns differ from decorator pattern.

References

<references />

Additional Reading