<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Knagar</id>
	<title>Expertiza_Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Knagar"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Knagar"/>
	<updated>2026-06-30T00:49:30Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.41.0</generator>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=71111</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=71111"/>
		<updated>2012-11-20T03:33:52Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Java */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter pattern,proxy pattern and composite pattern.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Coffee class with a method cost defining its cost as 2.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html&amp;lt;i&amp;gt;Decorator Pattern and more&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html&amp;lt;i&amp;gt;Implementing Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby&amp;lt;i&amp;gt;Gof Adapter Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html&amp;lt;i&amp;gt;Structural Patterns&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a [http://en.wikipedia.org/wiki/Sequence_diagram sequence diagram].&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable &amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-proxy&amp;lt;i&amp;gt;Proxy Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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. &amp;lt;ref&amp;gt;[http://www.oodesign.com/composite-pattern.html&amp;lt;i&amp;gt;Composite Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.rubybestpractices.com/posts/gregory/060-issue-26-structural-design-patterns.html&amp;lt;i&amp;gt;Implementation in ruby&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://www.oodesign.com/composite-pattern.html Composite Pattern]&lt;br /&gt;
*[http://javapapers.com/design-patterns/proxy-design-pattern/ Brief overview of proxy pattern]&lt;br /&gt;
*[http://javapapers.com/design-patterns/composite-design-pattern/ Brief overview of Composite Pattern]&lt;br /&gt;
*[http://blog.rubybestpractices.com/posts/gregory/060-issue-26-structural-design-patterns.html Patterns in Ruby]&lt;br /&gt;
*[http://www.simonecarletti.com/blog/2010/05/understanding-ruby-and-rails-proxy-patter-delegation-and-basicobject/ Proxy pattern in Ruby]&lt;br /&gt;
*[http://powerdream5.wordpress.com/2007/11/17/the-differences-between-decorator-pattern-and-proxy-pattern/ Differences between Proxy and Decorator pattern]&lt;br /&gt;
*[http://java.dzone.com/articles/design-patterns-composite composite Pattern]&lt;br /&gt;
*[http://www.codeproject.com/Articles/29036/Patterns-in-Real-Life Real life examples]&lt;br /&gt;
*[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Composite Pattern in Ruby]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=71109</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=71109"/>
		<updated>2012-11-20T03:33:05Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter pattern,proxy pattern and composite pattern.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Coffee class with a method cost defining its cost as 2.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html&amp;lt;i&amp;gt;Decorator Pattern and more&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html&amp;lt;i&amp;gt;Implementing Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby&amp;lt;i&amp;gt;Gof Adapter Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html&amp;lt;i&amp;gt;Structural Patterns&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a [http://en.wikipedia.org/wiki/Sequence_diagram sequence diagram].&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable &amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-proxy&amp;lt;i&amp;gt;Proxy Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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. &amp;lt;ref&amp;gt;[http://www.oodesign.com/composite-pattern.html&amp;lt;i&amp;gt;Composite Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.rubybestpractices.com/posts/gregory/060-issue-26-structural-design-patterns.html&amp;lt;i&amp;gt;Implementation in ruby&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://www.oodesign.com/composite-pattern.html Composite Pattern]&lt;br /&gt;
*[http://javapapers.com/design-patterns/proxy-design-pattern/ Brief overview of proxy pattern]&lt;br /&gt;
*[http://javapapers.com/design-patterns/composite-design-pattern/ Brief overview of Composite Pattern]&lt;br /&gt;
*[http://blog.rubybestpractices.com/posts/gregory/060-issue-26-structural-design-patterns.html Patterns in Ruby]&lt;br /&gt;
*[http://www.simonecarletti.com/blog/2010/05/understanding-ruby-and-rails-proxy-patter-delegation-and-basicobject/ Proxy pattern in Ruby]&lt;br /&gt;
*[http://powerdream5.wordpress.com/2007/11/17/the-differences-between-decorator-pattern-and-proxy-pattern/ Differences between Proxy and Decorator pattern]&lt;br /&gt;
*[http://java.dzone.com/articles/design-patterns-composite composite Pattern]&lt;br /&gt;
*[http://www.codeproject.com/Articles/29036/Patterns-in-Real-Life Real life examples]&lt;br /&gt;
*[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Composite Pattern in Ruby]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=71108</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=71108"/>
		<updated>2012-11-20T03:32:46Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter pattern,proxy pattern and composite pattern.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Coffee class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html&amp;lt;i&amp;gt;Decorator Pattern and more&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html&amp;lt;i&amp;gt;Implementing Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby&amp;lt;i&amp;gt;Gof Adapter Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html&amp;lt;i&amp;gt;Structural Patterns&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a [http://en.wikipedia.org/wiki/Sequence_diagram sequence diagram].&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable &amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-proxy&amp;lt;i&amp;gt;Proxy Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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. &amp;lt;ref&amp;gt;[http://www.oodesign.com/composite-pattern.html&amp;lt;i&amp;gt;Composite Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.rubybestpractices.com/posts/gregory/060-issue-26-structural-design-patterns.html&amp;lt;i&amp;gt;Implementation in ruby&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://www.oodesign.com/composite-pattern.html Composite Pattern]&lt;br /&gt;
*[http://javapapers.com/design-patterns/proxy-design-pattern/ Brief overview of proxy pattern]&lt;br /&gt;
*[http://javapapers.com/design-patterns/composite-design-pattern/ Brief overview of Composite Pattern]&lt;br /&gt;
*[http://blog.rubybestpractices.com/posts/gregory/060-issue-26-structural-design-patterns.html Patterns in Ruby]&lt;br /&gt;
*[http://www.simonecarletti.com/blog/2010/05/understanding-ruby-and-rails-proxy-patter-delegation-and-basicobject/ Proxy pattern in Ruby]&lt;br /&gt;
*[http://powerdream5.wordpress.com/2007/11/17/the-differences-between-decorator-pattern-and-proxy-pattern/ Differences between Proxy and Decorator pattern]&lt;br /&gt;
*[http://java.dzone.com/articles/design-patterns-composite composite Pattern]&lt;br /&gt;
*[http://www.codeproject.com/Articles/29036/Patterns-in-Real-Life Real life examples]&lt;br /&gt;
*[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Composite Pattern in Ruby]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=71107</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=71107"/>
		<updated>2012-11-20T03:31:59Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter pattern,proxy pattern and composite pattern.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html&amp;lt;i&amp;gt;Decorator Pattern and more&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html&amp;lt;i&amp;gt;Implementing Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby&amp;lt;i&amp;gt;Gof Adapter Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html&amp;lt;i&amp;gt;Structural Patterns&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a [http://en.wikipedia.org/wiki/Sequence_diagram sequence diagram].&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable &amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-proxy&amp;lt;i&amp;gt;Proxy Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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. &amp;lt;ref&amp;gt;[http://www.oodesign.com/composite-pattern.html&amp;lt;i&amp;gt;Composite Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.rubybestpractices.com/posts/gregory/060-issue-26-structural-design-patterns.html&amp;lt;i&amp;gt;Implementation in ruby&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://www.oodesign.com/composite-pattern.html Composite Pattern]&lt;br /&gt;
*[http://javapapers.com/design-patterns/proxy-design-pattern/ Brief overview of proxy pattern]&lt;br /&gt;
*[http://javapapers.com/design-patterns/composite-design-pattern/ Brief overview of Composite Pattern]&lt;br /&gt;
*[http://blog.rubybestpractices.com/posts/gregory/060-issue-26-structural-design-patterns.html Patterns in Ruby]&lt;br /&gt;
*[http://www.simonecarletti.com/blog/2010/05/understanding-ruby-and-rails-proxy-patter-delegation-and-basicobject/ Proxy pattern in Ruby]&lt;br /&gt;
*[http://powerdream5.wordpress.com/2007/11/17/the-differences-between-decorator-pattern-and-proxy-pattern/ Differences between Proxy and Decorator pattern]&lt;br /&gt;
*[http://java.dzone.com/articles/design-patterns-composite composite Pattern]&lt;br /&gt;
*[http://www.codeproject.com/Articles/29036/Patterns-in-Real-Life Real life examples]&lt;br /&gt;
*[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Composite Pattern in Ruby]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=71106</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=71106"/>
		<updated>2012-11-20T03:30:26Z</updated>

		<summary type="html">&lt;p&gt;Knagar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html&amp;lt;i&amp;gt;Decorator Pattern and more&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html&amp;lt;i&amp;gt;Implementing Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby&amp;lt;i&amp;gt;Gof Adapter Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html&amp;lt;i&amp;gt;Structural Patterns&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a [http://en.wikipedia.org/wiki/Sequence_diagram sequence diagram].&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable &amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-proxy&amp;lt;i&amp;gt;Proxy Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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. &amp;lt;ref&amp;gt;[http://www.oodesign.com/composite-pattern.html&amp;lt;i&amp;gt;Composite Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.rubybestpractices.com/posts/gregory/060-issue-26-structural-design-patterns.html&amp;lt;i&amp;gt;Implementation in ruby&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://www.oodesign.com/composite-pattern.html Composite Pattern]&lt;br /&gt;
*[http://javapapers.com/design-patterns/proxy-design-pattern/ Brief overview of proxy pattern]&lt;br /&gt;
*[http://javapapers.com/design-patterns/composite-design-pattern/ Brief overview of Composite Pattern]&lt;br /&gt;
*[http://blog.rubybestpractices.com/posts/gregory/060-issue-26-structural-design-patterns.html Patterns in Ruby]&lt;br /&gt;
*[http://www.simonecarletti.com/blog/2010/05/understanding-ruby-and-rails-proxy-patter-delegation-and-basicobject/ Proxy pattern in Ruby]&lt;br /&gt;
*[http://powerdream5.wordpress.com/2007/11/17/the-differences-between-decorator-pattern-and-proxy-pattern/ Differences between Proxy and Decorator pattern]&lt;br /&gt;
*[http://java.dzone.com/articles/design-patterns-composite composite Pattern]&lt;br /&gt;
*[http://www.codeproject.com/Articles/29036/Patterns-in-Real-Life Real life examples]&lt;br /&gt;
*[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Composite Pattern in Ruby]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=71104</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=71104"/>
		<updated>2012-11-20T03:29:57Z</updated>

		<summary type="html">&lt;p&gt;Knagar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;===Decorator and Related Patterns===&lt;br /&gt;
==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html&amp;lt;i&amp;gt;Decorator Pattern and more&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html&amp;lt;i&amp;gt;Implementing Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby&amp;lt;i&amp;gt;Gof Adapter Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html&amp;lt;i&amp;gt;Structural Patterns&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a [http://en.wikipedia.org/wiki/Sequence_diagram sequence diagram].&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable &amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-proxy&amp;lt;i&amp;gt;Proxy Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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. &amp;lt;ref&amp;gt;[http://www.oodesign.com/composite-pattern.html&amp;lt;i&amp;gt;Composite Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.rubybestpractices.com/posts/gregory/060-issue-26-structural-design-patterns.html&amp;lt;i&amp;gt;Implementation in ruby&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://www.oodesign.com/composite-pattern.html Composite Pattern]&lt;br /&gt;
*[http://javapapers.com/design-patterns/proxy-design-pattern/ Brief overview of proxy pattern]&lt;br /&gt;
*[http://javapapers.com/design-patterns/composite-design-pattern/ Brief overview of Composite Pattern]&lt;br /&gt;
*[http://blog.rubybestpractices.com/posts/gregory/060-issue-26-structural-design-patterns.html Patterns in Ruby]&lt;br /&gt;
*[http://www.simonecarletti.com/blog/2010/05/understanding-ruby-and-rails-proxy-patter-delegation-and-basicobject/ Proxy pattern in Ruby]&lt;br /&gt;
*[http://powerdream5.wordpress.com/2007/11/17/the-differences-between-decorator-pattern-and-proxy-pattern/ Differences between Proxy and Decorator pattern]&lt;br /&gt;
*[http://java.dzone.com/articles/design-patterns-composite composite Pattern]&lt;br /&gt;
*[http://www.codeproject.com/Articles/29036/Patterns-in-Real-Life Real life examples]&lt;br /&gt;
*[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Composite Pattern in Ruby]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70048</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70048"/>
		<updated>2012-11-18T03:24:17Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Intent */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html&amp;lt;i&amp;gt;Decorator Pattern and more&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html&amp;lt;i&amp;gt;Implementing Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby&amp;lt;i&amp;gt;Gof Adapter Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html&amp;lt;i&amp;gt;Structural Patterns&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70046</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70046"/>
		<updated>2012-11-18T03:23:38Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Intent */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html&amp;lt;i&amp;gt;Decorator Pattern and more&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html&amp;lt;i&amp;gt;Implementing Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby&amp;lt;i&amp;gt;Gof Adapter Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html&amp;lt;i&amp;gt;Structural Patterns&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70045</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70045"/>
		<updated>2012-11-18T03:23:02Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Decorator Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
===Decorator Pattern===&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html&amp;lt;i&amp;gt;Decorator Pattern and more&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html&amp;lt;i&amp;gt;Implementing Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby&amp;lt;i&amp;gt;Gof Adapter Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html&amp;lt;i&amp;gt;Structural Patterns&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70044</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70044"/>
		<updated>2012-11-18T03:18:20Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Difference between Decorator Pattern and Adapter Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html&amp;lt;i&amp;gt;Decorator Pattern and more&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html&amp;lt;i&amp;gt;Implementing Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby&amp;lt;i&amp;gt;Gof Adapter Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html&amp;lt;i&amp;gt;Structural Patterns&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70043</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70043"/>
		<updated>2012-11-18T03:17:14Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html&amp;lt;i&amp;gt;Decorator Pattern and more&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html&amp;lt;i&amp;gt;Implementing Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby&amp;lt;i&amp;gt;Gof Adapter Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70042</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70042"/>
		<updated>2012-11-18T03:15:41Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Java */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html&amp;lt;i&amp;gt;Decorator Pattern and more&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html&amp;lt;i&amp;gt;Implementing Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70041</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70041"/>
		<updated>2012-11-18T03:13:57Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html&amp;lt;i&amp;gt;Decorator Pattern and more&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70040</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70040"/>
		<updated>2012-11-18T03:13:16Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html&amp;lt;i&amp;gt;Example of Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70039</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70039"/>
		<updated>2012-11-18T03:11:39Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Decorator Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70038</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70038"/>
		<updated>2012-11-18T03:10:45Z</updated>

		<summary type="html">&lt;p&gt;Knagar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[&amp;lt;i&amp;gt;Decorator Pattern&amp;lt;/i&amp;gt;http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70037</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70037"/>
		<updated>2012-11-18T03:07:40Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Decorator Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;Decorator Pattern[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70036</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70036"/>
		<updated>2012-11-18T02:50:41Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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 &lt;br /&gt;
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.&lt;br /&gt;
features &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70034</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70034"/>
		<updated>2012-11-18T02:47:00Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Java */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The Adapter offers exactly the same interface as the adaptee, but it can override any method or add new ones.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70032</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70032"/>
		<updated>2012-11-18T02:46:00Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The Adapter offers exactly the same interface as the adaptee, but it can override any method or add new ones.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.scribd.com/doc/396559/gof-patterns-in-ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70031</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70031"/>
		<updated>2012-11-18T02:44:52Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The Adapter offers exactly the same interface as the adaptee, but it can override any method or add new ones.&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.new&lt;br /&gt;
adapter.talk&lt;br /&gt;
adapter.whine&lt;br /&gt;
adapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
output - &lt;br /&gt;
Let me introduce you to Adaptee!&lt;br /&gt;
I'm Adaptee&lt;br /&gt;
That was my adaptee&lt;br /&gt;
Stop bullying me!&lt;br /&gt;
I'm versatile&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70028</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70028"/>
		<updated>2012-11-18T02:39:10Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The Adapter offers exactly the same interface as the adaptee, but it can override any method or add new ones.&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.newadapter.talkadapter.whineadapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70027</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70027"/>
		<updated>2012-11-18T02:38:26Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The Adapter offers exactly the same interface as the adaptee, but it can override any method or add new ones.&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;&lt;br /&gt;
@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.newadapter.talkadapter.whineadapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Output------&lt;br /&gt;
GoF patterns in Ruby8/33 &lt;br /&gt;
Let me introduce you to Adaptee! I'm Adaptee That was my adaptee Stop bullying me!I'm versatile&lt;br /&gt;
GoF patterns in Ruby9/33&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70025</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70025"/>
		<updated>2012-11-18T02:36:50Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The Adapter offers exactly the same interface as the adaptee, but it can override any method or add new ones.&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adaptee &lt;br /&gt;
def talk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Adapter&lt;br /&gt;
def initialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.newadapter.talkadapter.whineadapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Output------&lt;br /&gt;
GoF patterns in Ruby8/33 &lt;br /&gt;
Let me introduce you to Adaptee!I'm AdapteeThat was my adapteeStop bullying me!I'm versatile&lt;br /&gt;
GoF patterns in Ruby9/33&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70023</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70023"/>
		<updated>2012-11-18T02:35:07Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
## The GoF Adapter pattern# written by Matthieu Tanguay-Carel## The Adapter offers exactly the same interface as the adaptee, but it can# override any method or add new ones.##&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
class Adapteedeftalk &lt;br /&gt;
puts &amp;quot;I'm Adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def&lt;br /&gt;
whine&lt;br /&gt;
 puts &amp;quot;Stop bullying me!&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
classAdapterdefinitialize&lt;br /&gt;
@adaptee=Adaptee.new&lt;br /&gt;
end&lt;br /&gt;
def talk&lt;br /&gt;
#override&lt;br /&gt;
 puts &amp;quot;Let me introduce you to Adaptee!&amp;quot;@adaptee.talk&lt;br /&gt;
 puts &amp;quot;That was my adaptee&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def do_other_stuff&lt;br /&gt;
 puts &amp;quot;I'm versatile&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
def method_missing method&lt;br /&gt;
if&lt;br /&gt;
@adaptee.respond_to? method@adaptee.sendmethod&lt;br /&gt;
else &lt;br /&gt;
raise NotImplementedError,&amp;quot;This method is not &amp;quot;+\ &amp;quot;available on this interface&amp;quot;&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
end&lt;br /&gt;
if__FILE__==$0&lt;br /&gt;
adapter=Adapter.newadapter.talkadapter.whineadapter.do_other_stuff&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Output------&lt;br /&gt;
GoF patterns in Ruby8/33 &lt;br /&gt;
Let me introduce you to Adaptee!I'm AdapteeThat was my adapteeStop bullying me!I'm versatile&lt;br /&gt;
GoF patterns in Ruby9/33&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70022</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70022"/>
		<updated>2012-11-18T02:26:06Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Difference between Decorator Pattern and Adapter Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://geekexplains.blogspot.com/2008/09/structural-patterns-adapter-decorator.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70021</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70021"/>
		<updated>2012-11-18T02:25:24Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Difference between Decorator Pattern and Adapter Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
Adapters can be used for decorating but their primary aim is to for enabling classes of different types not able to communicate&lt;br /&gt;
because of incompatible interface to interact via a adapter interface.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70015</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70015"/>
		<updated>2012-11-18T02:16:35Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Java */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.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]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70014</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70014"/>
		<updated>2012-11-18T02:15:57Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Java */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.This is our adaptee, a third party implementation of a number sorter that deals with Lists, not arrays. &amp;lt;pre&amp;gt;[http://java.dzone.com/articles/design-patterns-uncovered-0]&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70008</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70008"/>
		<updated>2012-11-18T02:07:44Z</updated>

		<summary type="html">&lt;p&gt;Knagar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
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.This is our adaptee, a third party implementation of a number sorter that deals with Lists, not arrays. &amp;lt;pre&amp;gt;[http://java.dzone.com/articles/design-patterns-uncovered-0]&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  public class NumberSorter&lt;br /&gt;
  {&lt;br /&gt;
  public List&amp;lt;Integer&amp;gt; sort(List&amp;lt;Integer&amp;gt; numbers)&lt;br /&gt;
  {&lt;br /&gt;
  //sort and return&lt;br /&gt;
  return new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
  }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
int[] numbers = new int[]{34, 2, 4, 12, 1}; &lt;br /&gt;
Sorter sorter = new SortListAdapter();&lt;br /&gt;
sorter.sort(numbers);&lt;br /&gt;
&lt;br /&gt;
We've provided a Sorter interface that expects the client input. This is our target.&lt;br /&gt;
//this is our Target interface&lt;br /&gt;
public interface Sorter&lt;br /&gt;
{&lt;br /&gt;
public int[] sort(int[] numbers);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter&lt;br /&gt;
&lt;br /&gt;
public class SortListAdapter implements Sorter&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public int[] sort(int[] numbers)&lt;br /&gt;
{&lt;br /&gt;
//convert the array to a List&lt;br /&gt;
List&amp;lt;Integer&amp;gt; numberList = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
//call the adapter&lt;br /&gt;
NumberSorter sorter = new NumberSorter();&lt;br /&gt;
numberList = sorter.sort(numberList);&lt;br /&gt;
&lt;br /&gt;
//convert the list back to an array and return &lt;br /&gt;
return sortedNumbers;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70007</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70007"/>
		<updated>2012-11-18T01:55:18Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Example */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Example===&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70006</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70006"/>
		<updated>2012-11-18T01:54:02Z</updated>

		<summary type="html">&lt;p&gt;Knagar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Example===&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
Match an existing object to a particular interface.&lt;br /&gt;
===Problem===&lt;br /&gt;
A system has the right data and behavior but the wrong interface. Typically used when you have to make something a&lt;br /&gt;
derivative of an abstract class you already have or are defining.&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.Solution: The adapter provides a “wrapper” with the desired&lt;br /&gt;
interface&lt;br /&gt;
===Example===&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70005</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70005"/>
		<updated>2012-11-18T01:39:40Z</updated>

		<summary type="html">&lt;p&gt;Knagar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Example===&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
brief overview&lt;br /&gt;
===Intent===&lt;br /&gt;
===Problem===&lt;br /&gt;
How to resolve incompatible interfaces or provide a stable interface to similar components with different interfaces?&lt;br /&gt;
===Solution===&lt;br /&gt;
Convert original interface component into another one through an intermediate adapter.&lt;br /&gt;
===Example===&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70004</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70004"/>
		<updated>2012-11-18T01:35:44Z</updated>

		<summary type="html">&lt;p&gt;Knagar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Example===&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example   &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2007/01/implementing-decorator-pattern-in-java.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
brief overview&lt;br /&gt;
===Intent===&lt;br /&gt;
===Problem===&lt;br /&gt;
===Solution===&lt;br /&gt;
===Example===&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70003</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70003"/>
		<updated>2012-11-18T01:31:39Z</updated>

		<summary type="html">&lt;p&gt;Knagar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and its related patterns such as adapter,proxy and composite.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Example===&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example    &lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this way we can add concrete decorator classes to provided the added functionality to the basic class.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
brief overview&lt;br /&gt;
===Intent===&lt;br /&gt;
===Problem===&lt;br /&gt;
===Solution===&lt;br /&gt;
===Example===&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70002</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=70002"/>
		<updated>2012-11-18T01:27:44Z</updated>

		<summary type="html">&lt;p&gt;Knagar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and compare it with related patterns such as adapter,proxy and composite pattern.w.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
brief overview&lt;br /&gt;
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.&lt;br /&gt;
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 &amp;quot;decorator.&amp;quot; We can use the one on the outside. It either masks, changes, or pass-throughs the methods of the instance inside of it. &amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider the typical example of a graphical window. To extend the functionality of the graphical window for example by adding a frame to the window, would require extending the window class to create a Framed Window class. To create a framed window it is necessary to create an object of the Framed Window class. However it would be impossible to start with a plain window and to extend its functionality at run time to become a framed &lt;br /&gt;
window.&amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Intent===&lt;br /&gt;
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality as provided by Gang of four. &amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
Add a decorator module , class that acts as a extender for functions at run time such that the calls are delegated to the decorator&lt;br /&gt;
to extend the functionality of the objects at run time.&lt;br /&gt;
===Example===&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
The example shows a Tea class with a method cost defining its cost as 4.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://lukeredpath.co.uk/blog/decorator-pattern-with-ruby-in-8-lines.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
If we want to calculate the cost of a cup of coffee. We have Coffee class, which implements a cost() method. &lt;br /&gt;
&lt;br /&gt;
class Coffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
But what if we want the cost of a coffee with milk? We could have a new class:&lt;br /&gt;
&lt;br /&gt;
class MilkCoffee&lt;br /&gt;
  def cost&lt;br /&gt;
    2.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
module Decorator&lt;br /&gt;
  def initialize(decorated)&lt;br /&gt;
    @decorated = decorated&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args)&lt;br /&gt;
    args.empty? ? @decorated.send(method) : @decorated.send(method, args)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
class Milk&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.4&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
class Whip&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost &lt;br /&gt;
    @decorated.cost + 0.2&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Sprinkles&lt;br /&gt;
  include Decorator&lt;br /&gt;
&lt;br /&gt;
  def cost&lt;br /&gt;
    @decorated.cost + 0.3&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
Whip.new(Coffee.new).cost&lt;br /&gt;
#=&amp;gt; 2.2&lt;br /&gt;
Sprinkles.new(Whip.new(Milk.new(Coffee.new))).cost&lt;br /&gt;
#=&amp;gt; 2.9&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
In this java example    &lt;br /&gt;
    basicInterface: Defines the interface for objects that can have responsibilities added to them dynamically.&lt;br /&gt;
    Basic: Defines an object to which additional responsibilities can be attached.&lt;br /&gt;
    Decorator: maintains a reference to a Basic object and defines an interface that conforms to Basic's interface.&lt;br /&gt;
    ConcreteDecorator: adds responsibilities to the component.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
    public interface basicInterface {&lt;br /&gt;
    public void do();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Basic implements basicInterface{&lt;br /&gt;
    public void do() {&lt;br /&gt;
    System.out.println(&amp;quot;Do basic stuff&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public interface Decorator extends basicInterface {&lt;br /&gt;
    public void addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class ConcreteDecorator implements Decorator {&lt;br /&gt;
&lt;br /&gt;
    basicInterface basic;&lt;br /&gt;
&lt;br /&gt;
    public ConcreteDecorator(basicInterface basic) {&lt;br /&gt;
    super();&lt;br /&gt;
    this.basic = basic;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void addedStuff() {&lt;br /&gt;
    System.out.println(&amp;quot;Decorator does other stuff too&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void do() {&lt;br /&gt;
    basic.do();&lt;br /&gt;
    addedStuff();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Client {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    basicInterface comp = new Basic();&lt;br /&gt;
    Decorator decorator = new ConcreteDecorator(comp);&lt;br /&gt;
    decorator.do();&lt;br /&gt;
    }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
brief overview&lt;br /&gt;
===Intent===&lt;br /&gt;
===Problem===&lt;br /&gt;
===Solution===&lt;br /&gt;
===Example===&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=69989</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=69989"/>
		<updated>2012-11-18T00:12:37Z</updated>

		<summary type="html">&lt;p&gt;Knagar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and compare it with related patterns such as adapter,proxy and composite pattern.w.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
brief overview&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.oodesign.com/decorator-pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
Consider the typical example of a graphical window. To extend the functionality of the graphical window for example by adding a frame to the window, would require extending the window class to create a Framed Window class. To create a framed window it is necessary to create an object of the Framed Window class. However it would be impossible to start with a plain window and to extend its functionality at run time to become a framed &lt;br /&gt;
window.&lt;br /&gt;
&lt;br /&gt;
===Intent===&lt;br /&gt;
An &lt;br /&gt;
===Problem===&lt;br /&gt;
===Solution===&lt;br /&gt;
===Example===&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
brief overview&lt;br /&gt;
===Intent===&lt;br /&gt;
===Problem===&lt;br /&gt;
===Solution===&lt;br /&gt;
===Example===&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=69988</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w39 ka</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w39_ka&amp;diff=69988"/>
		<updated>2012-11-18T00:10:41Z</updated>

		<summary type="html">&lt;p&gt;Knagar: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this section we will be discussing about the decorator pattern and compare it with related patterns such as adapter,proxy and composite pattern.w.&lt;br /&gt;
&lt;br /&gt;
==Decorator Pattern==&lt;br /&gt;
brief overview&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
[http://www.oodesign.com/decorator-pattern.html]Consider the typical example of a graphical window. To extend the functionality of the graphical window for example by adding a frame to the window, would require extending the window class to create a Framed Window class. To create a framed window it is necessary to create an object of the Framed Window class. However it would be impossible to start with a plain window and to extend its functionality at run time to become a framed &lt;br /&gt;
window.&lt;br /&gt;
&lt;br /&gt;
===Intent===&lt;br /&gt;
An &lt;br /&gt;
===Problem===&lt;br /&gt;
===Solution===&lt;br /&gt;
===Example===&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
brief overview&lt;br /&gt;
===Intent===&lt;br /&gt;
===Problem===&lt;br /&gt;
===Solution===&lt;br /&gt;
===Example===&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
brief explanation and Sample Code: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     type the code here&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Adapter Pattern===&lt;br /&gt;
&lt;br /&gt;
==Proxy Pattern==&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
&amp;quot;Provide a surrogate or placeholder for another object to control access to it” is the intent provided by GoF&amp;lt;ref&amp;gt;[http://c2.com/cgi/wiki?GangOfFour&amp;lt;i&amp;gt;&amp;quot;Gang of four&amp;quot;&amp;lt;/i&amp;gt;]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at the diagram definition before we go into more detail.&lt;br /&gt;
[[File:ProxyDesignPattern.png|none]]&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Let's take a look at this in action with a sequence diagram.&lt;br /&gt;
[[File:SequenceDiagramForProxy.png|none]]&lt;br /&gt;
&lt;br /&gt;
As you can see it's quite simple - the Proxy is providing a barrier between the client and the real implementation.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
There are four common situations in which the Proxy pattern is applicable.&lt;br /&gt;
&lt;br /&gt;
*A virtual proxy is a placeholder for “expensive to create” objects.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A remote proxy provides a local representative for an object that resides in a different address space. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A protective proxy controls access to a sensitive master object. &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*A smart proxy interposes additional actions when an object is accessed. Typical uses include: &lt;br /&gt;
**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),&lt;br /&gt;
**Loading a persistent object into memory when it’s first referenced,&lt;br /&gt;
**Checking that the real object is locked before it is accessed to ensure that no other object can change it.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
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.&lt;br /&gt;
Here’s a super simple bank Account.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
   class Account&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @amount = amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def deposit(amount)&lt;br /&gt;
    @amount += amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def withdraw(amount)&lt;br /&gt;
    @amount -= amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def balance&lt;br /&gt;
    @amount&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def inspect&lt;br /&gt;
    puts &amp;quot;Amount: #{@amount}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and here’s our AccountLogger class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class AccountLogger &amp;lt; BasicObject&lt;br /&gt;
&lt;br /&gt;
  def initialize(amount)&lt;br /&gt;
    @operations = []&lt;br /&gt;
&lt;br /&gt;
    @target = Account.new(amount)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [:initialize, [amount]]&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def method_missing(method, *args, &amp;amp;block)&lt;br /&gt;
    @operations &amp;lt;&amp;lt; [method, args]&lt;br /&gt;
    @target.send(method, *args, &amp;amp;block)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def operations&lt;br /&gt;
    @operations&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
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.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Animal {&lt;br /&gt;
 &lt;br /&gt;
   public void getSound();&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Lion implements Animal {&lt;br /&gt;
 &lt;br /&gt;
  public void getSound() {&lt;br /&gt;
     System.out.println(&amp;quot;Roar&amp;quot;);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.InvocationHandler;&lt;br /&gt;
import java.lang.reflect.Method;&lt;br /&gt;
 &lt;br /&gt;
public class AnimalInvocationHandler implements InvocationHandler {&lt;br /&gt;
  public AnimalInvocationHandler(Object realSubject) {&lt;br /&gt;
    this.realSubject = realSubject;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public Object invoke(Object proxy, Method m, Object[] args) {&lt;br /&gt;
    Object result = null;&lt;br /&gt;
    try {&lt;br /&gt;
      result = m.invoke(realSubject, args);&lt;br /&gt;
    } catch (Exception ex) {&lt;br /&gt;
      ex.printStackTrace();&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  private Object realSubject = null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.reflect.Proxy;&lt;br /&gt;
 &lt;br /&gt;
public class ProxyExample {&lt;br /&gt;
 &lt;br /&gt;
  public static void main(String[] args) {&lt;br /&gt;
    Animal realSubject = new Lion();&lt;br /&gt;
    Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()&lt;br /&gt;
        .getClassLoader(), realSubject.getClass().getInterfaces(),&lt;br /&gt;
        new AnimalInvocationHandler(realSubject));&lt;br /&gt;
    proxy.getSound();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have created a proxy handler that will be able to get the sound depending on the type of animal.&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Proxy Pattern===&lt;br /&gt;
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.        &lt;br /&gt;
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: &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
With the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively &lt;br /&gt;
constructed at runtime.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Composite Pattern==&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
===Intent===&lt;br /&gt;
“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.&lt;br /&gt;
===Problem===&lt;br /&gt;
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.&lt;br /&gt;
===Solution===&lt;br /&gt;
The figure below shows a UML class diagram for the Composite Pattern:&lt;br /&gt;
[[File:Composite.png|none]]&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*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.&lt;br /&gt;
*Client - The client manipulates objects in the hierarchy using the component interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===Example===&lt;br /&gt;
*GUI toolkits: &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*Destruction of objects in C++:&lt;br /&gt;
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.&lt;br /&gt;
Kill a node = Kill all its children and then kill yourself.&lt;br /&gt;
Since the children are also of type node, the loop continues till it goes to the lowest level where there are no children.&lt;br /&gt;
&lt;br /&gt;
In both the above mentioned cases using a composite pattern based recursion is a wise approach.&lt;br /&gt;
&lt;br /&gt;
===Implementation===&lt;br /&gt;
&lt;br /&gt;
====Ruby====&lt;br /&gt;
Use this in cases where your design seems to have a hierarchy. The hierarchy can be established  by data/logic i.e Tasks &amp;amp; SubTasks, Parts &amp;amp; SubParts.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     class Part&lt;br /&gt;
  def initialize name&lt;br /&gt;
    @name = name&lt;br /&gt;
  end&lt;br /&gt;
  def weight&lt;br /&gt;
    0&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Hand &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Hand&amp;quot;)&lt;br /&gt;
    @children = []&lt;br /&gt;
    5.times {add_child Finger.new}&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #component object&lt;br /&gt;
    weight &amp;amp;nbsp;= 5&lt;br /&gt;
    @children.each { |c| weight += c.weight }&lt;br /&gt;
    weight&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def add_child child&lt;br /&gt;
    @children &amp;lt;&amp;lt; child&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Finger &amp;lt; Part&lt;br /&gt;
  def initialize&lt;br /&gt;
    super(&amp;quot;Finger&amp;quot;)&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def weight #Leaf object&lt;br /&gt;
    1&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
hand = Hand.new&lt;br /&gt;
puts hand.weight #7&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Note here that the complex weight methods have been implemented in the component class and not the leaf class.&lt;br /&gt;
&lt;br /&gt;
====Java====&lt;br /&gt;
Here is the sample code that implements composite pattern.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    public class Block implements Group {&lt;br /&gt;
 &lt;br /&gt;
    public void assemble() {&lt;br /&gt;
        System.out.println(&amp;quot;Block&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public interface Group {&lt;br /&gt;
    public void assemble();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.util.ArrayList;&lt;br /&gt;
import java.util.List;&lt;br /&gt;
 &lt;br /&gt;
public class Structure implements Group {&lt;br /&gt;
  // Collection of child groups.&lt;br /&gt;
  private List&amp;lt;Group&amp;gt; groups = new ArrayList&amp;lt;Group&amp;gt;();&lt;br /&gt;
 &lt;br /&gt;
  public void assemble() {&lt;br /&gt;
    for (Group group : groups) {&lt;br /&gt;
      group.assemble();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Adds the group to the structure.&lt;br /&gt;
  public void add(Group group) {&lt;br /&gt;
    groups.add(group);&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  // Removes the group from the structure.&lt;br /&gt;
  public void remove(Group group) {&lt;br /&gt;
    groups.remove(group);&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class ImplementComposite {&lt;br /&gt;
   public static void main(String[] args) {&lt;br /&gt;
          //Initialize three blocks&lt;br /&gt;
          Block block1 = new Block();&lt;br /&gt;
          Block block2 = new Block();&lt;br /&gt;
          Block block3 = new Block();&lt;br /&gt;
 &lt;br /&gt;
          //Initialize three structure&lt;br /&gt;
          Structure structure = new Structure();&lt;br /&gt;
          Structure structure1 = new Structure();&lt;br /&gt;
          Structure structure2 = new Structure();&lt;br /&gt;
 &lt;br /&gt;
          //Composes the groups&lt;br /&gt;
          structure1.add(block1);&lt;br /&gt;
          structure1.add(block2);&lt;br /&gt;
 &lt;br /&gt;
          structure2.add(block3);&lt;br /&gt;
 &lt;br /&gt;
          structure.add(structure1);&lt;br /&gt;
          structure.add(structure2);&lt;br /&gt;
 &lt;br /&gt;
          structure.assemble();&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Difference between Decorator Pattern and Composite Pattern===&lt;br /&gt;
They usually go hand in and hand. In that using the composite pattern often leads to also using the decorator pattern.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
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].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
==Additional Reading==&lt;br /&gt;
*[http://tutorials.jenkov.com/java-reflection/classes.html Java Reflection]&lt;br /&gt;
*[http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply Java reflection basics]&lt;br /&gt;
*[http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/ref96/ref96.html A Tutorial on Behavioral Reflection and its Implementation]&lt;br /&gt;
*[http://www.quora.com/Computer-Programming/How-is-reflection-useful Uses of reflection]&lt;br /&gt;
*[http://download.oracle.com/javase/tutorial/reflect/index.html Java reflection official website]&lt;br /&gt;
*[http://ruby-doc.org/docs/ProgrammingRuby/html/builtins.html Ruby Documentation]&lt;br /&gt;
*[http://www.slideshare.net/MarcusDenker/behavioral-reflection Behavioral reflection]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/67ef8sbd(v=vs.80).aspx C# Basics]&lt;br /&gt;
*[http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx C# Reflection basics]&lt;br /&gt;
*[http://www.codeguru.com/csharp/csharp/cs_misc/reflection/article.php/c4257/An-Introduction-to-Reflection-in-C.htm Introduction to C# Reflection]&lt;br /&gt;
*[http://oreilly.com/catalog/progcsharp/chapter/ch18.html C# Attributes and Reflection]&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67256</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w67 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67256"/>
		<updated>2012-10-04T03:00:36Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Example - Session/Flash */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;                                                            &lt;br /&gt;
= Overview/Introduction =&lt;br /&gt;
&amp;lt;p&amp;gt; Redirection refers to redirection of incoming request from one page to another. HTTP is stateless, hence redirection with session/flash makes it stateful.As the http requests are stateless,it leads to losing the state of the previous request. Thus Rails provides hash called Flash which persist until the end of the next request received and Session hash, which unlike flash persists forever. &amp;lt;ref&amp;gt;http://www.youtube.com/watch?v=0m8lmRwS7E0&amp;lt;/ref&amp;gt;.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Flash in Ruby =&lt;br /&gt;
&amp;lt;p&amp;gt;Flash in ruby helps to remember the state until the end of the next request. It is basically used to store error messages as warnings and information as notice in the hash. It is used in views to print the error messages or notice. Along with notice and warnings, we can also define user defined hash and print its value in the view as we did for the notice and warnings. Basically it helps in flashing messages on the views. It stores values in the form of hash table. It is particularly useful to show messages after a redirect.Whenever we want to display any kind of status message or error message &amp;quot;Your email id is updated&amp;quot; or &amp;quot;Invalid Password&amp;quot; etc, flash is used to store that message.&lt;br /&gt;
Rails loads the flash when we set it in your controller code and it is displayed in your view. Rails discards the value when it is rendered on the client. The Flash values set in either notice/error or any user defined message in the controller can be accessed in the views to display the result of the action taken place in the controller.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Session in Ruby =&lt;br /&gt;
Most applications need to keep track of certain state of a particular user. Examples include shopping cart for online shopping account or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.&lt;br /&gt;
&lt;br /&gt;
A session usually consists of a hash of values and a session id, to identify the hash. Every cookie sent to the client’s browser includes the session id. And the other way round, the browser will send it to the server on every request from the client. &lt;br /&gt;
&lt;br /&gt;
In Ruby session persists forever and is stored in the browser cookies by default. The session data can thus be deleted by clearing content of the cookies. Session is useful when we have to remember the state for  a long time. Examples include Authentication where the user enters its login id and password that needs to be available for the complete session that the user is logged in. There are some alternative storage modes for session such as Storage table, No SQL data structure etc.&amp;lt;ref name=&amp;quot;ref5&amp;quot;&amp;gt; http://www.tutorialspoint.com/ruby-on-rails/rails-session-cookies.htm/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= How it works =&lt;br /&gt;
&lt;br /&gt;
== Session  ==&lt;br /&gt;
Session stores small amount of data that persists between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms such as cookies, tables, cache, memcache etc.&lt;br /&gt;
The session stores session id in cookies as it is insecure when embedded in the url.This unique id is used to look up the session data on its storage locations such as cookies, database tables, no sql data structure, cache etc.The data storage in cookies by default makes the session lightweight and easy to access and it does not requires calls to the storage locations for accessing the session data. The cookies can store atmost 4 kb data and hence leads to cookie overflow exception if the data in the session exceeds the 4 kb limit.The cookie data is not encrypted but it cannot be edited as well though it is visible in the url. &amp;lt;ref name=&amp;quot;ref1&amp;quot;&amp;gt; http://guides.rubyonrails.org/security.html#sessions/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
Session values are stored in a key,value pair.&lt;br /&gt;
&lt;br /&gt;
1. To add a session attribute we say &lt;br /&gt;
   session[:username]=params[:username]. &lt;br /&gt;
   Here we assign the username received from the user to the session variable.&lt;br /&gt;
2. To delete a session attribute value, just assign the key to nil.&lt;br /&gt;
   eg: session[:username]=nil. &lt;br /&gt;
   Here we are deleting the session attribute username.&lt;br /&gt;
3. The session can also be reset &lt;br /&gt;
   reset_session&lt;br /&gt;
   This will reset the complete session hash&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Flash is used by the controller to pass messages to the view. The controller can pass messages about the success or failure of the desired action. In Ruby,we can also pass the flash message as part of the redirection informing the view about the state of the action performed when redirecting. The user can also pass user defined messages and also pass messages for debugging purposes.The layout that receives the flash has to decide the action to be performed on the basis of the message received from the flash.&amp;lt;ref name=&amp;quot;ref4&amp;quot;&amp;gt;http://guides.rubyonrails.org/action_controller_overview.html#the-flash &amp;lt;/ref&amp;gt;&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. To set a  flash value as a notice &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
   flash[:notice]= &amp;quot;User logged in successfully&amp;quot; &lt;br /&gt;
   The flash message sets the notice value. This flashes the notice on the form when the user successfully logs into the system.  &lt;br /&gt;
&lt;br /&gt;
2. To set a flash value as a warning &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
    flash[:error]= &amp;quot;Please provide the username and password&amp;quot; &lt;br /&gt;
    The flash message sets the error value. This automatically flashes the notice saying that the user did not provide the username and password.  &lt;br /&gt;
&lt;br /&gt;
3. To set flash message as part of redirection&lt;br /&gt;
   redirect_to( posts_show,  :notice =&amp;gt; &amp;quot;Post successfully created&amp;quot; )&lt;br /&gt;
   The above statement redirects the method call to the appropriate url and displays a notice there automatically saying the post was successfully &lt;br /&gt;
   created.&lt;br /&gt;
&lt;br /&gt;
4. The value of flash to be saved for the subsequent requests&lt;br /&gt;
   flash.keep&lt;br /&gt;
   The above statement keeps all values of flash, that resulted from the redirection, to be used in the subsequent requests.&lt;br /&gt;
&lt;br /&gt;
5.  The value of flash to be saved in the current request &lt;br /&gt;
    flash.now&lt;br /&gt;
    The above statement keeps the values of flash, that resulted from the redirection, to be used for the current request.&lt;br /&gt;
&lt;br /&gt;
= Example - Session/Flash =&lt;br /&gt;
&lt;br /&gt;
:Class ExamplesController &amp;lt; ApplicationController&amp;lt;br&amp;gt;&lt;br /&gt;
::def index&lt;br /&gt;
::'''session[:example_name]=params[:example][:name]'''&lt;br /&gt;
::...&lt;br /&gt;
::end&lt;br /&gt;
::def update&lt;br /&gt;
:::@example = Example.find(params[:id])&lt;br /&gt;
:::respond_to do |format|&lt;br /&gt;
::::if @example.update_attributes(params[:type])&lt;br /&gt;
:::::format.html {redirect_to(@example, '''flash[:notice] =&amp;gt; 'Example was successfully updated.'''')}&lt;br /&gt;
::::else&lt;br /&gt;
:::::format.html { render :action =&amp;gt; &amp;quot;edit&amp;quot; }&lt;br /&gt;
::::end&lt;br /&gt;
:::end&lt;br /&gt;
::end&lt;br /&gt;
::def &lt;br /&gt;
::....&lt;br /&gt;
::end&lt;br /&gt;
:end&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''In the show(@example) view, we can make use of session and flash as- '''&lt;br /&gt;
&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;notice&amp;quot;&amp;gt;&amp;lt;%=notice%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;example name&amp;quot;&amp;gt;&amp;lt;%=session[:example_name]%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above code, the ExampleController class has a index method that sets the session for the user and &lt;br /&gt;
update method sets the flash variable ,we set the session variable with the name of the example obtained from&lt;br /&gt;
the user stored in the params hash, we can access it in any view in that session.In the update method, flash is used to set&lt;br /&gt;
the notice to a desired value. Then it is used in the view to display the message.&lt;br /&gt;
&lt;br /&gt;
= Advantages/Disadvantages =&lt;br /&gt;
&lt;br /&gt;
== Session &amp;lt;ref name=&amp;quot;ref6&amp;quot;&amp;gt; http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions_controller &amp;lt;/ref&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
'''Session Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 1.A session object helps us store useful information about the application like the session_id, currently logged in user details. &amp;lt;br&amp;gt;&lt;br /&gt;
 2.It is similar to hash and helps us take advantages of the hash functionalities in Ruby. &amp;lt;br&amp;gt;&lt;br /&gt;
 3.Since, it persists forever, the session variables can be used to perform authentication,server side validation and take care of the security aspects &lt;br /&gt;
   of the application. &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Session Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. The session object is a heavy weight object as it is used to store a lot of application related information.&amp;lt;br&amp;gt;&lt;br /&gt;
2. we have to be careful while dealing with session variables as it is subject to malicious attacks and sensitive information can be divulged if not &lt;br /&gt;
   taken care of while programming. &amp;lt;br&amp;gt;&lt;br /&gt;
3. As the session variables persists forever, it is the programmers responsibility to reset the information of the application when the application goes &lt;br /&gt;
   out of the current scope logically. &amp;lt;br&amp;gt;&lt;br /&gt;
4. Too many session variable manipulation and storage can make the code inefficient and can cause unexpected behaviour if not programmed carefully.&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&lt;br /&gt;
'''Flash Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. A lightweight object that helps us store the information of the state the application is in.&amp;lt;br&amp;gt;&lt;br /&gt;
2. Since flash is similar to hash, it helps us abuse the advantages of hash. &amp;lt;br&amp;gt;&lt;br /&gt;
3. Any key can be passed into the flash object and the user is responsible for extracting the information from the corresponding object &amp;lt;br&amp;gt;&lt;br /&gt;
4. It is less tedious to manage as its lifetime persists only until the next request.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. As the information stored in the flash object persists only until the next request, it is not useful for providing security related capabilities to &lt;br /&gt;
   the application.&amp;lt;br&amp;gt;&lt;br /&gt;
2. It has limited capabilities and used for displaying simple error messages, notices or warnings in the application.&amp;lt;br&amp;gt;&lt;br /&gt;
3. It cannot store dynamic information.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion/Summary =&lt;br /&gt;
&lt;br /&gt;
HTTP is a stateless protocol and the web applications require saving of the application state frequently. Based on the application state, certain actions are taken. This is possible in RUBY using redirection flash object. The redirection flash object persists for a short duration and helps us store simple information about the application. Another flash like object that provides us very rich capabilities in terms of information storge, authentication and security is the session object. We have seen the differences between the two. It is the programmers responsibility to appropriately use the flash or the session object depending on what needs to be achieved.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67251</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w67 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67251"/>
		<updated>2012-10-04T02:59:05Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Flash */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;                                                            &lt;br /&gt;
= Overview/Introduction =&lt;br /&gt;
&amp;lt;p&amp;gt; Redirection refers to redirection of incoming request from one page to another. HTTP is stateless, hence redirection with session/flash makes it stateful.As the http requests are stateless,it leads to losing the state of the previous request. Thus Rails provides hash called Flash which persist until the end of the next request received and Session hash, which unlike flash persists forever. &amp;lt;ref&amp;gt;http://www.youtube.com/watch?v=0m8lmRwS7E0&amp;lt;/ref&amp;gt;.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Flash in Ruby =&lt;br /&gt;
&amp;lt;p&amp;gt;Flash in ruby helps to remember the state until the end of the next request. It is basically used to store error messages as warnings and information as notice in the hash. It is used in views to print the error messages or notice. Along with notice and warnings, we can also define user defined hash and print its value in the view as we did for the notice and warnings. Basically it helps in flashing messages on the views. It stores values in the form of hash table. It is particularly useful to show messages after a redirect.Whenever we want to display any kind of status message or error message &amp;quot;Your email id is updated&amp;quot; or &amp;quot;Invalid Password&amp;quot; etc, flash is used to store that message.&lt;br /&gt;
Rails loads the flash when we set it in your controller code and it is displayed in your view. Rails discards the value when it is rendered on the client. The Flash values set in either notice/error or any user defined message in the controller can be accessed in the views to display the result of the action taken place in the controller.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Session in Ruby =&lt;br /&gt;
Most applications need to keep track of certain state of a particular user. Examples include shopping cart for online shopping account or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.&lt;br /&gt;
&lt;br /&gt;
A session usually consists of a hash of values and a session id, to identify the hash. Every cookie sent to the client’s browser includes the session id. And the other way round, the browser will send it to the server on every request from the client. &lt;br /&gt;
&lt;br /&gt;
In Ruby session persists forever and is stored in the browser cookies by default. The session data can thus be deleted by clearing content of the cookies. Session is useful when we have to remember the state for  a long time. Examples include Authentication where the user enters its login id and password that needs to be available for the complete session that the user is logged in. There are some alternative storage modes for session such as Storage table, No SQL data structure etc.&amp;lt;ref name=&amp;quot;ref5&amp;quot;&amp;gt; http://www.tutorialspoint.com/ruby-on-rails/rails-session-cookies.htm/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= How it works =&lt;br /&gt;
&lt;br /&gt;
== Session  ==&lt;br /&gt;
Session stores small amount of data that persists between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms such as cookies, tables, cache, memcache etc.&lt;br /&gt;
The session stores session id in cookies as it is insecure when embedded in the url.This unique id is used to look up the session data on its storage locations such as cookies, database tables, no sql data structure, cache etc.The data storage in cookies by default makes the session lightweight and easy to access and it does not requires calls to the storage locations for accessing the session data. The cookies can store atmost 4 kb data and hence leads to cookie overflow exception if the data in the session exceeds the 4 kb limit.The cookie data is not encrypted but it cannot be edited as well though it is visible in the url. &amp;lt;ref name=&amp;quot;ref1&amp;quot;&amp;gt; http://guides.rubyonrails.org/security.html#sessions/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
Session values are stored in a key,value pair.&lt;br /&gt;
&lt;br /&gt;
1. To add a session attribute we say &lt;br /&gt;
   session[:username]=params[:username]. &lt;br /&gt;
   Here we assign the username received from the user to the session variable.&lt;br /&gt;
2. To delete a session attribute value, just assign the key to nil.&lt;br /&gt;
   eg: session[:username]=nil. &lt;br /&gt;
   Here we are deleting the session attribute username.&lt;br /&gt;
3. The session can also be reset &lt;br /&gt;
   reset_session&lt;br /&gt;
   This will reset the complete session hash&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Flash is used by the controller to pass messages to the view. The controller can pass messages about the success or failure of the desired action. In Ruby,we can also pass the flash message as part of the redirection informing the view about the state of the action performed when redirecting. The user can also pass user defined messages and also pass messages for debugging purposes.The layout that receives the flash has to decide the action to be performed on the basis of the message received from the flash.&amp;lt;ref name=&amp;quot;ref4&amp;quot;&amp;gt;http://guides.rubyonrails.org/action_controller_overview.html#the-flash &amp;lt;/ref&amp;gt;&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. To set a  flash value as a notice &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
   flash[:notice]= &amp;quot;User logged in successfully&amp;quot; &lt;br /&gt;
   The flash message sets the notice value. This flashes the notice on the form when the user successfully logs into the system.  &lt;br /&gt;
&lt;br /&gt;
2. To set a flash value as a warning &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
    flash[:error]= &amp;quot;Please provide the username and password&amp;quot; &lt;br /&gt;
    The flash message sets the error value. This automatically flashes the notice saying that the user did not provide the username and password.  &lt;br /&gt;
&lt;br /&gt;
3. To set flash message as part of redirection&lt;br /&gt;
   redirect_to( posts_show,  :notice =&amp;gt; &amp;quot;Post successfully created&amp;quot; )&lt;br /&gt;
   The above statement redirects the method call to the appropriate url and displays a notice there automatically saying the post was successfully &lt;br /&gt;
   created.&lt;br /&gt;
&lt;br /&gt;
4. The value of flash to be saved for the subsequent requests&lt;br /&gt;
   flash.keep&lt;br /&gt;
   The above statement keeps all values of flash, that resulted from the redirection, to be used in the subsequent requests.&lt;br /&gt;
&lt;br /&gt;
5.  The value of flash to be saved in the current request &lt;br /&gt;
    flash.now&lt;br /&gt;
    The above statement keeps the values of flash, that resulted from the redirection, to be used for the current request.&lt;br /&gt;
&lt;br /&gt;
= Example - Session/Flash =&lt;br /&gt;
&lt;br /&gt;
:Class ExamplesController &amp;lt; ApplicationController&amp;lt;br&amp;gt;&lt;br /&gt;
::def index&lt;br /&gt;
::'''session[:example_name]=params[:example][:name]'''&lt;br /&gt;
::...&lt;br /&gt;
::end&lt;br /&gt;
::def update&lt;br /&gt;
:::@example = Example.find(params[:id])&lt;br /&gt;
:::respond_to do |format|&lt;br /&gt;
::::if @example.update_attributes(params[:type])&lt;br /&gt;
:::::format.html {redirect_to(@example, '''flash[:notice] =&amp;gt; 'Example was successfully updated.'''')}&lt;br /&gt;
::::else&lt;br /&gt;
:::::format.html { render :action =&amp;gt; &amp;quot;edit&amp;quot; }&lt;br /&gt;
::::end&lt;br /&gt;
:::end&lt;br /&gt;
::end&lt;br /&gt;
::def &lt;br /&gt;
::....&lt;br /&gt;
::end&lt;br /&gt;
:end&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''In the show(@example) view, we can make use of session and flash as- '''&lt;br /&gt;
&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;notice&amp;quot;&amp;gt;&amp;lt;%=notice%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;example name&amp;quot;&amp;gt;&amp;lt;%=session[:example_name]%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above code, the ExampleController class has a index method that sets the session for the user and &lt;br /&gt;
update method that sets the flash variable ,we set the session variable with the name of the example obtained from&lt;br /&gt;
the user stored in the params hash, we can access it in any view in that session.In the update method, flash is used to set&lt;br /&gt;
the notice to a desired value. Then it is used in the view  to display the message.&lt;br /&gt;
&lt;br /&gt;
= Advantages/Disadvantages =&lt;br /&gt;
&lt;br /&gt;
== Session &amp;lt;ref name=&amp;quot;ref6&amp;quot;&amp;gt; http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions_controller &amp;lt;/ref&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
'''Session Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 1.A session object helps us store useful information about the application like the session_id, currently logged in user details. &amp;lt;br&amp;gt;&lt;br /&gt;
 2.It is similar to hash and helps us take advantages of the hash functionalities in Ruby. &amp;lt;br&amp;gt;&lt;br /&gt;
 3.Since, it persists forever, the session variables can be used to perform authentication,server side validation and take care of the security aspects &lt;br /&gt;
   of the application. &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Session Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. The session object is a heavy weight object as it is used to store a lot of application related information.&amp;lt;br&amp;gt;&lt;br /&gt;
2. we have to be careful while dealing with session variables as it is subject to malicious attacks and sensitive information can be divulged if not &lt;br /&gt;
   taken care of while programming. &amp;lt;br&amp;gt;&lt;br /&gt;
3. As the session variables persists forever, it is the programmers responsibility to reset the information of the application when the application goes &lt;br /&gt;
   out of the current scope logically. &amp;lt;br&amp;gt;&lt;br /&gt;
4. Too many session variable manipulation and storage can make the code inefficient and can cause unexpected behaviour if not programmed carefully.&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&lt;br /&gt;
'''Flash Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. A lightweight object that helps us store the information of the state the application is in.&amp;lt;br&amp;gt;&lt;br /&gt;
2. Since flash is similar to hash, it helps us abuse the advantages of hash. &amp;lt;br&amp;gt;&lt;br /&gt;
3. Any key can be passed into the flash object and the user is responsible for extracting the information from the corresponding object &amp;lt;br&amp;gt;&lt;br /&gt;
4. It is less tedious to manage as its lifetime persists only until the next request.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. As the information stored in the flash object persists only until the next request, it is not useful for providing security related capabilities to &lt;br /&gt;
   the application.&amp;lt;br&amp;gt;&lt;br /&gt;
2. It has limited capabilities and used for displaying simple error messages, notices or warnings in the application.&amp;lt;br&amp;gt;&lt;br /&gt;
3. It cannot store dynamic information.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion/Summary =&lt;br /&gt;
&lt;br /&gt;
HTTP is a stateless protocol and the web applications require saving of the application state frequently. Based on the application state, certain actions are taken. This is possible in RUBY using redirection flash object. The redirection flash object persists for a short duration and helps us store simple information about the application. Another flash like object that provides us very rich capabilities in terms of information storge, authentication and security is the session object. We have seen the differences between the two. It is the programmers responsibility to appropriately use the flash or the session object depending on what needs to be achieved.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67243</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w67 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67243"/>
		<updated>2012-10-04T02:56:32Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Session */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;                                                            &lt;br /&gt;
= Overview/Introduction =&lt;br /&gt;
&amp;lt;p&amp;gt; Redirection refers to redirection of incoming request from one page to another. HTTP is stateless, hence redirection with session/flash makes it stateful.As the http requests are stateless,it leads to losing the state of the previous request. Thus Rails provides hash called Flash which persist until the end of the next request received and Session hash, which unlike flash persists forever. &amp;lt;ref&amp;gt;http://www.youtube.com/watch?v=0m8lmRwS7E0&amp;lt;/ref&amp;gt;.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Flash in Ruby =&lt;br /&gt;
&amp;lt;p&amp;gt;Flash in ruby helps to remember the state until the end of the next request. It is basically used to store error messages as warnings and information as notice in the hash. It is used in views to print the error messages or notice. Along with notice and warnings, we can also define user defined hash and print its value in the view as we did for the notice and warnings. Basically it helps in flashing messages on the views. It stores values in the form of hash table. It is particularly useful to show messages after a redirect.Whenever we want to display any kind of status message or error message &amp;quot;Your email id is updated&amp;quot; or &amp;quot;Invalid Password&amp;quot; etc, flash is used to store that message.&lt;br /&gt;
Rails loads the flash when we set it in your controller code and it is displayed in your view. Rails discards the value when it is rendered on the client. The Flash values set in either notice/error or any user defined message in the controller can be accessed in the views to display the result of the action taken place in the controller.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Session in Ruby =&lt;br /&gt;
Most applications need to keep track of certain state of a particular user. Examples include shopping cart for online shopping account or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.&lt;br /&gt;
&lt;br /&gt;
A session usually consists of a hash of values and a session id, to identify the hash. Every cookie sent to the client’s browser includes the session id. And the other way round, the browser will send it to the server on every request from the client. &lt;br /&gt;
&lt;br /&gt;
In Ruby session persists forever and is stored in the browser cookies by default. The session data can thus be deleted by clearing content of the cookies. Session is useful when we have to remember the state for  a long time. Examples include Authentication where the user enters its login id and password that needs to be available for the complete session that the user is logged in. There are some alternative storage modes for session such as Storage table, No SQL data structure etc.&amp;lt;ref name=&amp;quot;ref5&amp;quot;&amp;gt; http://www.tutorialspoint.com/ruby-on-rails/rails-session-cookies.htm/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= How it works =&lt;br /&gt;
&lt;br /&gt;
== Session  ==&lt;br /&gt;
Session stores small amount of data that persists between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms such as cookies, tables, cache, memcache etc.&lt;br /&gt;
The session stores session id in cookies as it is insecure when embedded in the url.This unique id is used to look up the session data on its storage locations such as cookies, database tables, no sql data structure, cache etc.The data storage in cookies by default makes the session lightweight and easy to access and it does not requires calls to the storage locations for accessing the session data. The cookies can store atmost 4 kb data and hence leads to cookie overflow exception if the data in the session exceeds the 4 kb limit.The cookie data is not encrypted but it cannot be edited as well though it is visible in the url. &amp;lt;ref name=&amp;quot;ref1&amp;quot;&amp;gt; http://guides.rubyonrails.org/security.html#sessions/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
Session values are stored in a key,value pair.&lt;br /&gt;
&lt;br /&gt;
1. To add a session attribute we say &lt;br /&gt;
   session[:username]=params[:username]. &lt;br /&gt;
   Here we assign the username received from the user to the session variable.&lt;br /&gt;
2. To delete a session attribute value, just assign the key to nil.&lt;br /&gt;
   eg: session[:username]=nil. &lt;br /&gt;
   Here we are deleting the session attribute username.&lt;br /&gt;
3. The session can also be reset &lt;br /&gt;
   reset_session&lt;br /&gt;
   This will reset the complete session hash&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Flash is used by the controller to pass messages to the view. The controller can pass messages about the success or failure of the desired action. In Ruby,w e can also pass the flash message as part of the redirection again informing the view about the state of the action performed when redirecting. The user can also pass user defined messages and also pass messages for debugging purposes. The flash message displayed on the form/view is now taken care by the next request. The layout that receives the flash has to decide the action to be performed on the basis of the message received from the flash.&amp;lt;ref name=&amp;quot;ref4&amp;quot;&amp;gt;http://guides.rubyonrails.org/action_controller_overview.html#the-flash &amp;lt;/ref&amp;gt;&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. To set a  flash value as a notice &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
   flash[:notice]= &amp;quot;User logged in successfully&amp;quot; &lt;br /&gt;
   The flash message sets the notice value. This flashes the notice on the form when the user successfully logs into the system.  &lt;br /&gt;
&lt;br /&gt;
2. To set a flash value as a warning &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
    flash[:error]= &amp;quot;Please provide the username and password&amp;quot; &lt;br /&gt;
    The flash message sets the error value. This automatically flashes the notice saying that the user did not provide the username and password.  &lt;br /&gt;
&lt;br /&gt;
3. To set flash message as part of redirection&lt;br /&gt;
   redirect_to( posts_show,  :notice =&amp;gt; &amp;quot;Post successfully created&amp;quot; )&lt;br /&gt;
   The above statement redirects the method call to the appropriate url and displays a notice there automatically saying the post was successfully &lt;br /&gt;
   created.&lt;br /&gt;
&lt;br /&gt;
4. The value of flash to be saved for the subsequent requests&lt;br /&gt;
   flash.keep&lt;br /&gt;
   The above statement keeps all values of flash, that resulted from the redirection, to be used in the subsequent requests.&lt;br /&gt;
&lt;br /&gt;
5.  The value of flash to be saved in the current request &lt;br /&gt;
    flash.now&lt;br /&gt;
    The above statement keeps the values of flash, that resulted from the redirection, to be used for the current request.&lt;br /&gt;
&lt;br /&gt;
= Example - Session/Flash =&lt;br /&gt;
&lt;br /&gt;
:Class ExamplesController &amp;lt; ApplicationController&amp;lt;br&amp;gt;&lt;br /&gt;
::def index&lt;br /&gt;
::'''session[:example_name]=params[:example][:name]'''&lt;br /&gt;
::...&lt;br /&gt;
::end&lt;br /&gt;
::def update&lt;br /&gt;
:::@example = Example.find(params[:id])&lt;br /&gt;
:::respond_to do |format|&lt;br /&gt;
::::if @example.update_attributes(params[:type])&lt;br /&gt;
:::::format.html {redirect_to(@example, '''flash[:notice] =&amp;gt; 'Example was successfully updated.'''')}&lt;br /&gt;
::::else&lt;br /&gt;
:::::format.html { render :action =&amp;gt; &amp;quot;edit&amp;quot; }&lt;br /&gt;
::::end&lt;br /&gt;
:::end&lt;br /&gt;
::end&lt;br /&gt;
::def &lt;br /&gt;
::....&lt;br /&gt;
::end&lt;br /&gt;
:end&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''In the show(@example) view, we can make use of session and flash as- '''&lt;br /&gt;
&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;notice&amp;quot;&amp;gt;&amp;lt;%=notice%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;example name&amp;quot;&amp;gt;&amp;lt;%=session[:example_name]%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above code, the ExampleController class has a index method that sets the session for the user and &lt;br /&gt;
update method that sets the flash variable ,we set the session variable with the name of the example obtained from&lt;br /&gt;
the user stored in the params hash, we can access it in any view in that session.In the update method, flash is used to set&lt;br /&gt;
the notice to a desired value. Then it is used in the view  to display the message.&lt;br /&gt;
&lt;br /&gt;
= Advantages/Disadvantages =&lt;br /&gt;
&lt;br /&gt;
== Session &amp;lt;ref name=&amp;quot;ref6&amp;quot;&amp;gt; http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions_controller &amp;lt;/ref&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
'''Session Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 1.A session object helps us store useful information about the application like the session_id, currently logged in user details. &amp;lt;br&amp;gt;&lt;br /&gt;
 2.It is similar to hash and helps us take advantages of the hash functionalities in Ruby. &amp;lt;br&amp;gt;&lt;br /&gt;
 3.Since, it persists forever, the session variables can be used to perform authentication,server side validation and take care of the security aspects &lt;br /&gt;
   of the application. &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Session Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. The session object is a heavy weight object as it is used to store a lot of application related information.&amp;lt;br&amp;gt;&lt;br /&gt;
2. we have to be careful while dealing with session variables as it is subject to malicious attacks and sensitive information can be divulged if not &lt;br /&gt;
   taken care of while programming. &amp;lt;br&amp;gt;&lt;br /&gt;
3. As the session variables persists forever, it is the programmers responsibility to reset the information of the application when the application goes &lt;br /&gt;
   out of the current scope logically. &amp;lt;br&amp;gt;&lt;br /&gt;
4. Too many session variable manipulation and storage can make the code inefficient and can cause unexpected behaviour if not programmed carefully.&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&lt;br /&gt;
'''Flash Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. A lightweight object that helps us store the information of the state the application is in.&amp;lt;br&amp;gt;&lt;br /&gt;
2. Since flash is similar to hash, it helps us abuse the advantages of hash. &amp;lt;br&amp;gt;&lt;br /&gt;
3. Any key can be passed into the flash object and the user is responsible for extracting the information from the corresponding object &amp;lt;br&amp;gt;&lt;br /&gt;
4. It is less tedious to manage as its lifetime persists only until the next request.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. As the information stored in the flash object persists only until the next request, it is not useful for providing security related capabilities to &lt;br /&gt;
   the application.&amp;lt;br&amp;gt;&lt;br /&gt;
2. It has limited capabilities and used for displaying simple error messages, notices or warnings in the application.&amp;lt;br&amp;gt;&lt;br /&gt;
3. It cannot store dynamic information.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion/Summary =&lt;br /&gt;
&lt;br /&gt;
HTTP is a stateless protocol and the web applications require saving of the application state frequently. Based on the application state, certain actions are taken. This is possible in RUBY using redirection flash object. The redirection flash object persists for a short duration and helps us store simple information about the application. Another flash like object that provides us very rich capabilities in terms of information storge, authentication and security is the session object. We have seen the differences between the two. It is the programmers responsibility to appropriately use the flash or the session object depending on what needs to be achieved.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67239</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w67 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67239"/>
		<updated>2012-10-04T02:53:49Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Session in Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;                                                            &lt;br /&gt;
= Overview/Introduction =&lt;br /&gt;
&amp;lt;p&amp;gt; Redirection refers to redirection of incoming request from one page to another. HTTP is stateless, hence redirection with session/flash makes it stateful.As the http requests are stateless,it leads to losing the state of the previous request. Thus Rails provides hash called Flash which persist until the end of the next request received and Session hash, which unlike flash persists forever. &amp;lt;ref&amp;gt;http://www.youtube.com/watch?v=0m8lmRwS7E0&amp;lt;/ref&amp;gt;.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Flash in Ruby =&lt;br /&gt;
&amp;lt;p&amp;gt;Flash in ruby helps to remember the state until the end of the next request. It is basically used to store error messages as warnings and information as notice in the hash. It is used in views to print the error messages or notice. Along with notice and warnings, we can also define user defined hash and print its value in the view as we did for the notice and warnings. Basically it helps in flashing messages on the views. It stores values in the form of hash table. It is particularly useful to show messages after a redirect.Whenever we want to display any kind of status message or error message &amp;quot;Your email id is updated&amp;quot; or &amp;quot;Invalid Password&amp;quot; etc, flash is used to store that message.&lt;br /&gt;
Rails loads the flash when we set it in your controller code and it is displayed in your view. Rails discards the value when it is rendered on the client. The Flash values set in either notice/error or any user defined message in the controller can be accessed in the views to display the result of the action taken place in the controller.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Session in Ruby =&lt;br /&gt;
Most applications need to keep track of certain state of a particular user. Examples include shopping cart for online shopping account or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.&lt;br /&gt;
&lt;br /&gt;
A session usually consists of a hash of values and a session id, to identify the hash. Every cookie sent to the client’s browser includes the session id. And the other way round, the browser will send it to the server on every request from the client. &lt;br /&gt;
&lt;br /&gt;
In Ruby session persists forever and is stored in the browser cookies by default. The session data can thus be deleted by clearing content of the cookies. Session is useful when we have to remember the state for  a long time. Examples include Authentication where the user enters its login id and password that needs to be available for the complete session that the user is logged in. There are some alternative storage modes for session such as Storage table, No SQL data structure etc.&amp;lt;ref name=&amp;quot;ref5&amp;quot;&amp;gt; http://www.tutorialspoint.com/ruby-on-rails/rails-session-cookies.htm/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= How it works =&lt;br /&gt;
&lt;br /&gt;
== Session  ==&lt;br /&gt;
Session stores small amount of data that persists between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms such as cookies, tables, cache, memcache etc.&lt;br /&gt;
The session stores session id in cookies as it is insecure when embedded in the url.This unique id is used to look up the session data on its storage locations such as cookies, database tables, no sql data structure, cache etc.The data storage in cookies by default makes the session lightweight and easy to access and it does not requires calls to the storage locations for accessing the session data. The cookies can store atmost 4 kb data and hence gives cookie overflow exception if the data in the session exceeds the 4 kb limit.The cookie data is not encrypted but it cannot be edited by being visible in the url. &amp;lt;ref name=&amp;quot;ref1&amp;quot;&amp;gt; http://guides.rubyonrails.org/security.html#sessions/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
Session values are stored in a key,value pair. In Ruby we store it like a hash.&lt;br /&gt;
&lt;br /&gt;
1. To add a session attribute we say &lt;br /&gt;
   session[:username]=params[:username]. &lt;br /&gt;
   Here we assign the username received from the user to the session variable.&lt;br /&gt;
2. To delete a session attribute value, just assign the key to nil.&lt;br /&gt;
   eg: session[:username]=nil. &lt;br /&gt;
   Here we are deleting the session attribute username.&lt;br /&gt;
3. The session can also be reset &lt;br /&gt;
   reset_session&lt;br /&gt;
   This will reset the complete session hash&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Flash is used by the controller to pass messages to the view. The controller can pass messages about the success or failure of the desired action. In Ruby,w e can also pass the flash message as part of the redirection again informing the view about the state of the action performed when redirecting. The user can also pass user defined messages and also pass messages for debugging purposes. The flash message displayed on the form/view is now taken care by the next request. The layout that receives the flash has to decide the action to be performed on the basis of the message received from the flash.&amp;lt;ref name=&amp;quot;ref4&amp;quot;&amp;gt;http://guides.rubyonrails.org/action_controller_overview.html#the-flash &amp;lt;/ref&amp;gt;&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. To set a  flash value as a notice &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
   flash[:notice]= &amp;quot;User logged in successfully&amp;quot; &lt;br /&gt;
   The flash message sets the notice value. This flashes the notice on the form when the user successfully logs into the system.  &lt;br /&gt;
&lt;br /&gt;
2. To set a flash value as a warning &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
    flash[:error]= &amp;quot;Please provide the username and password&amp;quot; &lt;br /&gt;
    The flash message sets the error value. This automatically flashes the notice saying that the user did not provide the username and password.  &lt;br /&gt;
&lt;br /&gt;
3. To set flash message as part of redirection&lt;br /&gt;
   redirect_to( posts_show,  :notice =&amp;gt; &amp;quot;Post successfully created&amp;quot; )&lt;br /&gt;
   The above statement redirects the method call to the appropriate url and displays a notice there automatically saying the post was successfully &lt;br /&gt;
   created.&lt;br /&gt;
&lt;br /&gt;
4. The value of flash to be saved for the subsequent requests&lt;br /&gt;
   flash.keep&lt;br /&gt;
   The above statement keeps all values of flash, that resulted from the redirection, to be used in the subsequent requests.&lt;br /&gt;
&lt;br /&gt;
5.  The value of flash to be saved in the current request &lt;br /&gt;
    flash.now&lt;br /&gt;
    The above statement keeps the values of flash, that resulted from the redirection, to be used for the current request.&lt;br /&gt;
&lt;br /&gt;
= Example - Session/Flash =&lt;br /&gt;
&lt;br /&gt;
:Class ExamplesController &amp;lt; ApplicationController&amp;lt;br&amp;gt;&lt;br /&gt;
::def index&lt;br /&gt;
::'''session[:example_name]=params[:example][:name]'''&lt;br /&gt;
::...&lt;br /&gt;
::end&lt;br /&gt;
::def update&lt;br /&gt;
:::@example = Example.find(params[:id])&lt;br /&gt;
:::respond_to do |format|&lt;br /&gt;
::::if @example.update_attributes(params[:type])&lt;br /&gt;
:::::format.html {redirect_to(@example, '''flash[:notice] =&amp;gt; 'Example was successfully updated.'''')}&lt;br /&gt;
::::else&lt;br /&gt;
:::::format.html { render :action =&amp;gt; &amp;quot;edit&amp;quot; }&lt;br /&gt;
::::end&lt;br /&gt;
:::end&lt;br /&gt;
::end&lt;br /&gt;
::def &lt;br /&gt;
::....&lt;br /&gt;
::end&lt;br /&gt;
:end&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''In the show(@example) view, we can make use of session and flash as- '''&lt;br /&gt;
&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;notice&amp;quot;&amp;gt;&amp;lt;%=notice%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;example name&amp;quot;&amp;gt;&amp;lt;%=session[:example_name]%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above code, the ExampleController class has a index method that sets the session for the user and &lt;br /&gt;
update method that sets the flash variable ,we set the session variable with the name of the example obtained from&lt;br /&gt;
the user stored in the params hash, we can access it in any view in that session.In the update method, flash is used to set&lt;br /&gt;
the notice to a desired value. Then it is used in the view  to display the message.&lt;br /&gt;
&lt;br /&gt;
= Advantages/Disadvantages =&lt;br /&gt;
&lt;br /&gt;
== Session &amp;lt;ref name=&amp;quot;ref6&amp;quot;&amp;gt; http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions_controller &amp;lt;/ref&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
'''Session Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 1.A session object helps us store useful information about the application like the session_id, currently logged in user details. &amp;lt;br&amp;gt;&lt;br /&gt;
 2.It is similar to hash and helps us take advantages of the hash functionalities in Ruby. &amp;lt;br&amp;gt;&lt;br /&gt;
 3.Since, it persists forever, the session variables can be used to perform authentication,server side validation and take care of the security aspects &lt;br /&gt;
   of the application. &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Session Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. The session object is a heavy weight object as it is used to store a lot of application related information.&amp;lt;br&amp;gt;&lt;br /&gt;
2. we have to be careful while dealing with session variables as it is subject to malicious attacks and sensitive information can be divulged if not &lt;br /&gt;
   taken care of while programming. &amp;lt;br&amp;gt;&lt;br /&gt;
3. As the session variables persists forever, it is the programmers responsibility to reset the information of the application when the application goes &lt;br /&gt;
   out of the current scope logically. &amp;lt;br&amp;gt;&lt;br /&gt;
4. Too many session variable manipulation and storage can make the code inefficient and can cause unexpected behaviour if not programmed carefully.&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&lt;br /&gt;
'''Flash Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. A lightweight object that helps us store the information of the state the application is in.&amp;lt;br&amp;gt;&lt;br /&gt;
2. Since flash is similar to hash, it helps us abuse the advantages of hash. &amp;lt;br&amp;gt;&lt;br /&gt;
3. Any key can be passed into the flash object and the user is responsible for extracting the information from the corresponding object &amp;lt;br&amp;gt;&lt;br /&gt;
4. It is less tedious to manage as its lifetime persists only until the next request.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. As the information stored in the flash object persists only until the next request, it is not useful for providing security related capabilities to &lt;br /&gt;
   the application.&amp;lt;br&amp;gt;&lt;br /&gt;
2. It has limited capabilities and used for displaying simple error messages, notices or warnings in the application.&amp;lt;br&amp;gt;&lt;br /&gt;
3. It cannot store dynamic information.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion/Summary =&lt;br /&gt;
&lt;br /&gt;
HTTP is a stateless protocol and the web applications require saving of the application state frequently. Based on the application state, certain actions are taken. This is possible in RUBY using redirection flash object. The redirection flash object persists for a short duration and helps us store simple information about the application. Another flash like object that provides us very rich capabilities in terms of information storge, authentication and security is the session object. We have seen the differences between the two. It is the programmers responsibility to appropriately use the flash or the session object depending on what needs to be achieved.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67238</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w67 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67238"/>
		<updated>2012-10-04T02:52:12Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Flash in Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;                                                            &lt;br /&gt;
= Overview/Introduction =&lt;br /&gt;
&amp;lt;p&amp;gt; Redirection refers to redirection of incoming request from one page to another. HTTP is stateless, hence redirection with session/flash makes it stateful.As the http requests are stateless,it leads to losing the state of the previous request. Thus Rails provides hash called Flash which persist until the end of the next request received and Session hash, which unlike flash persists forever. &amp;lt;ref&amp;gt;http://www.youtube.com/watch?v=0m8lmRwS7E0&amp;lt;/ref&amp;gt;.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Flash in Ruby =&lt;br /&gt;
&amp;lt;p&amp;gt;Flash in ruby helps to remember the state until the end of the next request. It is basically used to store error messages as warnings and information as notice in the hash. It is used in views to print the error messages or notice. Along with notice and warnings, we can also define user defined hash and print its value in the view as we did for the notice and warnings. Basically it helps in flashing messages on the views. It stores values in the form of hash table. It is particularly useful to show messages after a redirect.Whenever we want to display any kind of status message or error message &amp;quot;Your email id is updated&amp;quot; or &amp;quot;Invalid Password&amp;quot; etc, flash is used to store that message.&lt;br /&gt;
Rails loads the flash when we set it in your controller code and it is displayed in your view. Rails discards the value when it is rendered on the client. The Flash values set in either notice/error or any user defined message in the controller can be accessed in the views to display the result of the action taken place in the controller.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Session in Ruby =&lt;br /&gt;
Most applications need to keep track of certain state of a particular user. Examples include shopping cart for online shopping account or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.&lt;br /&gt;
&lt;br /&gt;
A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client’s browser includes the session id. And the other way round, the browser will send it to the server on every request from the client. &lt;br /&gt;
&lt;br /&gt;
In Ruby session persists forever and is stored in the browser cookies by default. The session data can thus be deleted by clearing content of the cookies. Session is useful when we have to remember the state for  a long time. Examples include Authentication where the user enters its login id and password that needs to be available for the whole session that the user is logged in. There are some alternative storage modes for session such as Storage table or No SQL data structure.&amp;lt;ref name=&amp;quot;ref5&amp;quot;&amp;gt; http://www.tutorialspoint.com/ruby-on-rails/rails-session-cookies.htm/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= How it works =&lt;br /&gt;
&lt;br /&gt;
== Session  ==&lt;br /&gt;
Session stores small amount of data that persists between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms such as cookies, tables, cache, memcache etc.&lt;br /&gt;
The session stores session id in cookies as it is insecure when embedded in the url.This unique id is used to look up the session data on its storage locations such as cookies, database tables, no sql data structure, cache etc.The data storage in cookies by default makes the session lightweight and easy to access and it does not requires calls to the storage locations for accessing the session data. The cookies can store atmost 4 kb data and hence gives cookie overflow exception if the data in the session exceeds the 4 kb limit.The cookie data is not encrypted but it cannot be edited by being visible in the url. &amp;lt;ref name=&amp;quot;ref1&amp;quot;&amp;gt; http://guides.rubyonrails.org/security.html#sessions/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
Session values are stored in a key,value pair. In Ruby we store it like a hash.&lt;br /&gt;
&lt;br /&gt;
1. To add a session attribute we say &lt;br /&gt;
   session[:username]=params[:username]. &lt;br /&gt;
   Here we assign the username received from the user to the session variable.&lt;br /&gt;
2. To delete a session attribute value, just assign the key to nil.&lt;br /&gt;
   eg: session[:username]=nil. &lt;br /&gt;
   Here we are deleting the session attribute username.&lt;br /&gt;
3. The session can also be reset &lt;br /&gt;
   reset_session&lt;br /&gt;
   This will reset the complete session hash&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Flash is used by the controller to pass messages to the view. The controller can pass messages about the success or failure of the desired action. In Ruby,w e can also pass the flash message as part of the redirection again informing the view about the state of the action performed when redirecting. The user can also pass user defined messages and also pass messages for debugging purposes. The flash message displayed on the form/view is now taken care by the next request. The layout that receives the flash has to decide the action to be performed on the basis of the message received from the flash.&amp;lt;ref name=&amp;quot;ref4&amp;quot;&amp;gt;http://guides.rubyonrails.org/action_controller_overview.html#the-flash &amp;lt;/ref&amp;gt;&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. To set a  flash value as a notice &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
   flash[:notice]= &amp;quot;User logged in successfully&amp;quot; &lt;br /&gt;
   The flash message sets the notice value. This flashes the notice on the form when the user successfully logs into the system.  &lt;br /&gt;
&lt;br /&gt;
2. To set a flash value as a warning &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
    flash[:error]= &amp;quot;Please provide the username and password&amp;quot; &lt;br /&gt;
    The flash message sets the error value. This automatically flashes the notice saying that the user did not provide the username and password.  &lt;br /&gt;
&lt;br /&gt;
3. To set flash message as part of redirection&lt;br /&gt;
   redirect_to( posts_show,  :notice =&amp;gt; &amp;quot;Post successfully created&amp;quot; )&lt;br /&gt;
   The above statement redirects the method call to the appropriate url and displays a notice there automatically saying the post was successfully &lt;br /&gt;
   created.&lt;br /&gt;
&lt;br /&gt;
4. The value of flash to be saved for the subsequent requests&lt;br /&gt;
   flash.keep&lt;br /&gt;
   The above statement keeps all values of flash, that resulted from the redirection, to be used in the subsequent requests.&lt;br /&gt;
&lt;br /&gt;
5.  The value of flash to be saved in the current request &lt;br /&gt;
    flash.now&lt;br /&gt;
    The above statement keeps the values of flash, that resulted from the redirection, to be used for the current request.&lt;br /&gt;
&lt;br /&gt;
= Example - Session/Flash =&lt;br /&gt;
&lt;br /&gt;
:Class ExamplesController &amp;lt; ApplicationController&amp;lt;br&amp;gt;&lt;br /&gt;
::def index&lt;br /&gt;
::'''session[:example_name]=params[:example][:name]'''&lt;br /&gt;
::...&lt;br /&gt;
::end&lt;br /&gt;
::def update&lt;br /&gt;
:::@example = Example.find(params[:id])&lt;br /&gt;
:::respond_to do |format|&lt;br /&gt;
::::if @example.update_attributes(params[:type])&lt;br /&gt;
:::::format.html {redirect_to(@example, '''flash[:notice] =&amp;gt; 'Example was successfully updated.'''')}&lt;br /&gt;
::::else&lt;br /&gt;
:::::format.html { render :action =&amp;gt; &amp;quot;edit&amp;quot; }&lt;br /&gt;
::::end&lt;br /&gt;
:::end&lt;br /&gt;
::end&lt;br /&gt;
::def &lt;br /&gt;
::....&lt;br /&gt;
::end&lt;br /&gt;
:end&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''In the show(@example) view, we can make use of session and flash as- '''&lt;br /&gt;
&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;notice&amp;quot;&amp;gt;&amp;lt;%=notice%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;example name&amp;quot;&amp;gt;&amp;lt;%=session[:example_name]%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above code, the ExampleController class has a index method that sets the session for the user and &lt;br /&gt;
update method that sets the flash variable ,we set the session variable with the name of the example obtained from&lt;br /&gt;
the user stored in the params hash, we can access it in any view in that session.In the update method, flash is used to set&lt;br /&gt;
the notice to a desired value. Then it is used in the view  to display the message.&lt;br /&gt;
&lt;br /&gt;
= Advantages/Disadvantages =&lt;br /&gt;
&lt;br /&gt;
== Session &amp;lt;ref name=&amp;quot;ref6&amp;quot;&amp;gt; http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions_controller &amp;lt;/ref&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
'''Session Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 1.A session object helps us store useful information about the application like the session_id, currently logged in user details. &amp;lt;br&amp;gt;&lt;br /&gt;
 2.It is similar to hash and helps us take advantages of the hash functionalities in Ruby. &amp;lt;br&amp;gt;&lt;br /&gt;
 3.Since, it persists forever, the session variables can be used to perform authentication,server side validation and take care of the security aspects &lt;br /&gt;
   of the application. &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Session Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. The session object is a heavy weight object as it is used to store a lot of application related information.&amp;lt;br&amp;gt;&lt;br /&gt;
2. we have to be careful while dealing with session variables as it is subject to malicious attacks and sensitive information can be divulged if not &lt;br /&gt;
   taken care of while programming. &amp;lt;br&amp;gt;&lt;br /&gt;
3. As the session variables persists forever, it is the programmers responsibility to reset the information of the application when the application goes &lt;br /&gt;
   out of the current scope logically. &amp;lt;br&amp;gt;&lt;br /&gt;
4. Too many session variable manipulation and storage can make the code inefficient and can cause unexpected behaviour if not programmed carefully.&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&lt;br /&gt;
'''Flash Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. A lightweight object that helps us store the information of the state the application is in.&amp;lt;br&amp;gt;&lt;br /&gt;
2. Since flash is similar to hash, it helps us abuse the advantages of hash. &amp;lt;br&amp;gt;&lt;br /&gt;
3. Any key can be passed into the flash object and the user is responsible for extracting the information from the corresponding object &amp;lt;br&amp;gt;&lt;br /&gt;
4. It is less tedious to manage as its lifetime persists only until the next request.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. As the information stored in the flash object persists only until the next request, it is not useful for providing security related capabilities to &lt;br /&gt;
   the application.&amp;lt;br&amp;gt;&lt;br /&gt;
2. It has limited capabilities and used for displaying simple error messages, notices or warnings in the application.&amp;lt;br&amp;gt;&lt;br /&gt;
3. It cannot store dynamic information.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion/Summary =&lt;br /&gt;
&lt;br /&gt;
HTTP is a stateless protocol and the web applications require saving of the application state frequently. Based on the application state, certain actions are taken. This is possible in RUBY using redirection flash object. The redirection flash object persists for a short duration and helps us store simple information about the application. Another flash like object that provides us very rich capabilities in terms of information storge, authentication and security is the session object. We have seen the differences between the two. It is the programmers responsibility to appropriately use the flash or the session object depending on what needs to be achieved.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67234</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w67 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67234"/>
		<updated>2012-10-04T02:49:47Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Overview/Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;                                                            &lt;br /&gt;
= Overview/Introduction =&lt;br /&gt;
&amp;lt;p&amp;gt; Redirection refers to redirection of incoming request from one page to another. HTTP is stateless, hence redirection with session/flash makes it stateful.As the http requests are stateless,it leads to losing the state of the previous request. Thus Rails provides hash called Flash which persist until the end of the next request received and Session hash, which unlike flash persists forever. &amp;lt;ref&amp;gt;http://www.youtube.com/watch?v=0m8lmRwS7E0&amp;lt;/ref&amp;gt;.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Flash in Ruby =&lt;br /&gt;
&amp;lt;p&amp;gt;Flash in ruby helps to remember the state until the end of the next request. It is basically used to store error messages as warnings and information as notice in the hash. This is used in views to print the error messages or notice. Instead of notice or warnings, we can define user defined hash and print its value in the view as we did for the notice and warnings. Basically it helps in flashing messages on the views. It stores values in the form of hash table. It is particularly useful to show messages after a redirect.Whenever you want to display any kind of status message or error message &amp;quot;Your email id is updated&amp;quot; or &amp;quot;Invalid Password&amp;quot; etc.&lt;br /&gt;
Rails loads it when you set it in your controller code and it is displayed in your view (if you have it set to display in the view). Rails discards the value when it is rendered on the client. The Flash values set in either notice/error or any user defined message in the controller can be accessed in the views to display the result of the action taken place in the controller.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Session in Ruby =&lt;br /&gt;
Most applications need to keep track of certain state of a particular user. Examples include shopping cart for online shopping account or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.&lt;br /&gt;
&lt;br /&gt;
A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client’s browser includes the session id. And the other way round, the browser will send it to the server on every request from the client. &lt;br /&gt;
&lt;br /&gt;
In Ruby session persists forever and is stored in the browser cookies by default. The session data can thus be deleted by clearing content of the cookies. Session is useful when we have to remember the state for  a long time. Examples include Authentication where the user enters its login id and password that needs to be available for the whole session that the user is logged in. There are some alternative storage modes for session such as Storage table or No SQL data structure.&amp;lt;ref name=&amp;quot;ref5&amp;quot;&amp;gt; http://www.tutorialspoint.com/ruby-on-rails/rails-session-cookies.htm/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= How it works =&lt;br /&gt;
&lt;br /&gt;
== Session  ==&lt;br /&gt;
Session stores small amount of data that persists between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms such as cookies, tables, cache, memcache etc.&lt;br /&gt;
The session stores session id in cookies as it is insecure when embedded in the url.This unique id is used to look up the session data on its storage locations such as cookies, database tables, no sql data structure, cache etc.The data storage in cookies by default makes the session lightweight and easy to access and it does not requires calls to the storage locations for accessing the session data. The cookies can store atmost 4 kb data and hence gives cookie overflow exception if the data in the session exceeds the 4 kb limit.The cookie data is not encrypted but it cannot be edited by being visible in the url. &amp;lt;ref name=&amp;quot;ref1&amp;quot;&amp;gt; http://guides.rubyonrails.org/security.html#sessions/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
Session values are stored in a key,value pair. In Ruby we store it like a hash.&lt;br /&gt;
&lt;br /&gt;
1. To add a session attribute we say &lt;br /&gt;
   session[:username]=params[:username]. &lt;br /&gt;
   Here we assign the username received from the user to the session variable.&lt;br /&gt;
2. To delete a session attribute value, just assign the key to nil.&lt;br /&gt;
   eg: session[:username]=nil. &lt;br /&gt;
   Here we are deleting the session attribute username.&lt;br /&gt;
3. The session can also be reset &lt;br /&gt;
   reset_session&lt;br /&gt;
   This will reset the complete session hash&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Flash is used by the controller to pass messages to the view. The controller can pass messages about the success or failure of the desired action. In Ruby,w e can also pass the flash message as part of the redirection again informing the view about the state of the action performed when redirecting. The user can also pass user defined messages and also pass messages for debugging purposes. The flash message displayed on the form/view is now taken care by the next request. The layout that receives the flash has to decide the action to be performed on the basis of the message received from the flash.&amp;lt;ref name=&amp;quot;ref4&amp;quot;&amp;gt;http://guides.rubyonrails.org/action_controller_overview.html#the-flash &amp;lt;/ref&amp;gt;&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. To set a  flash value as a notice &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
   flash[:notice]= &amp;quot;User logged in successfully&amp;quot; &lt;br /&gt;
   The flash message sets the notice value. This flashes the notice on the form when the user successfully logs into the system.  &lt;br /&gt;
&lt;br /&gt;
2. To set a flash value as a warning &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
    flash[:error]= &amp;quot;Please provide the username and password&amp;quot; &lt;br /&gt;
    The flash message sets the error value. This automatically flashes the notice saying that the user did not provide the username and password.  &lt;br /&gt;
&lt;br /&gt;
3. To set flash message as part of redirection&lt;br /&gt;
   redirect_to( posts_show,  :notice =&amp;gt; &amp;quot;Post successfully created&amp;quot; )&lt;br /&gt;
   The above statement redirects the method call to the appropriate url and displays a notice there automatically saying the post was successfully &lt;br /&gt;
   created.&lt;br /&gt;
&lt;br /&gt;
4. The value of flash to be saved for the subsequent requests&lt;br /&gt;
   flash.keep&lt;br /&gt;
   The above statement keeps all values of flash, that resulted from the redirection, to be used in the subsequent requests.&lt;br /&gt;
&lt;br /&gt;
5.  The value of flash to be saved in the current request &lt;br /&gt;
    flash.now&lt;br /&gt;
    The above statement keeps the values of flash, that resulted from the redirection, to be used for the current request.&lt;br /&gt;
&lt;br /&gt;
= Example - Session/Flash =&lt;br /&gt;
&lt;br /&gt;
:Class ExamplesController &amp;lt; ApplicationController&amp;lt;br&amp;gt;&lt;br /&gt;
::def index&lt;br /&gt;
::'''session[:example_name]=params[:example][:name]'''&lt;br /&gt;
::...&lt;br /&gt;
::end&lt;br /&gt;
::def update&lt;br /&gt;
:::@example = Example.find(params[:id])&lt;br /&gt;
:::respond_to do |format|&lt;br /&gt;
::::if @example.update_attributes(params[:type])&lt;br /&gt;
:::::format.html {redirect_to(@example, '''flash[:notice] =&amp;gt; 'Example was successfully updated.'''')}&lt;br /&gt;
::::else&lt;br /&gt;
:::::format.html { render :action =&amp;gt; &amp;quot;edit&amp;quot; }&lt;br /&gt;
::::end&lt;br /&gt;
:::end&lt;br /&gt;
::end&lt;br /&gt;
::def &lt;br /&gt;
::....&lt;br /&gt;
::end&lt;br /&gt;
:end&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''In the show(@example) view, we can make use of session and flash as- '''&lt;br /&gt;
&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;notice&amp;quot;&amp;gt;&amp;lt;%=notice%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;example name&amp;quot;&amp;gt;&amp;lt;%=session[:example_name]%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above code, the ExampleController class has a index method that sets the session for the user and &lt;br /&gt;
update method that sets the flash variable ,we set the session variable with the name of the example obtained from&lt;br /&gt;
the user stored in the params hash, we can access it in any view in that session.In the update method, flash is used to set&lt;br /&gt;
the notice to a desired value. Then it is used in the view  to display the message.&lt;br /&gt;
&lt;br /&gt;
= Advantages/Disadvantages =&lt;br /&gt;
&lt;br /&gt;
== Session &amp;lt;ref name=&amp;quot;ref6&amp;quot;&amp;gt; http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions_controller &amp;lt;/ref&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
'''Session Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 1.A session object helps us store useful information about the application like the session_id, currently logged in user details. &amp;lt;br&amp;gt;&lt;br /&gt;
 2.It is similar to hash and helps us take advantages of the hash functionalities in Ruby. &amp;lt;br&amp;gt;&lt;br /&gt;
 3.Since, it persists forever, the session variables can be used to perform authentication,server side validation and take care of the security aspects &lt;br /&gt;
   of the application. &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Session Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. The session object is a heavy weight object as it is used to store a lot of application related information.&amp;lt;br&amp;gt;&lt;br /&gt;
2. we have to be careful while dealing with session variables as it is subject to malicious attacks and sensitive information can be divulged if not &lt;br /&gt;
   taken care of while programming. &amp;lt;br&amp;gt;&lt;br /&gt;
3. As the session variables persists forever, it is the programmers responsibility to reset the information of the application when the application goes &lt;br /&gt;
   out of the current scope logically. &amp;lt;br&amp;gt;&lt;br /&gt;
4. Too many session variable manipulation and storage can make the code inefficient and can cause unexpected behaviour if not programmed carefully.&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&lt;br /&gt;
'''Flash Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. A lightweight object that helps us store the information of the state the application is in.&amp;lt;br&amp;gt;&lt;br /&gt;
2. Since flash is similar to hash, it helps us abuse the advantages of hash. &amp;lt;br&amp;gt;&lt;br /&gt;
3. Any key can be passed into the flash object and the user is responsible for extracting the information from the corresponding object &amp;lt;br&amp;gt;&lt;br /&gt;
4. It is less tedious to manage as its lifetime persists only until the next request.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. As the information stored in the flash object persists only until the next request, it is not useful for providing security related capabilities to &lt;br /&gt;
   the application.&amp;lt;br&amp;gt;&lt;br /&gt;
2. It has limited capabilities and used for displaying simple error messages, notices or warnings in the application.&amp;lt;br&amp;gt;&lt;br /&gt;
3. It cannot store dynamic information.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion/Summary =&lt;br /&gt;
&lt;br /&gt;
HTTP is a stateless protocol and the web applications require saving of the application state frequently. Based on the application state, certain actions are taken. This is possible in RUBY using redirection flash object. The redirection flash object persists for a short duration and helps us store simple information about the application. Another flash like object that provides us very rich capabilities in terms of information storge, authentication and security is the session object. We have seen the differences between the two. It is the programmers responsibility to appropriately use the flash or the session object depending on what needs to be achieved.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67232</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w67 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67232"/>
		<updated>2012-10-04T02:49:25Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Overview/Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;                                                            &lt;br /&gt;
= Overview/Introduction =&lt;br /&gt;
&amp;lt;p&amp;gt; Redirection refers to redirection of incoming request from one page to another. HTTP is stateless, hence redirection with session/flash makes it stateful.As the http requests are stateless,it leads to losing the state of the previous request. Thus Rails provides hash called Flash which persist until the end of the next request received and Session hash, which unlike flash persists forever. &amp;lt;ref&amp;gt;http://www.youtube.com/watch?v=0m8lmRwS7E0&amp;lt;/ref&amp;gt;.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p&amp;gt;For information on how to format the text of your article, create tables, and use section headings and references, see this [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/WIKI_Features article].&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Flash in Ruby =&lt;br /&gt;
&amp;lt;p&amp;gt;Flash in ruby helps to remember the state until the end of the next request. It is basically used to store error messages as warnings and information as notice in the hash. This is used in views to print the error messages or notice. Instead of notice or warnings, we can define user defined hash and print its value in the view as we did for the notice and warnings. Basically it helps in flashing messages on the views. It stores values in the form of hash table. It is particularly useful to show messages after a redirect.Whenever you want to display any kind of status message or error message &amp;quot;Your email id is updated&amp;quot; or &amp;quot;Invalid Password&amp;quot; etc.&lt;br /&gt;
Rails loads it when you set it in your controller code and it is displayed in your view (if you have it set to display in the view). Rails discards the value when it is rendered on the client. The Flash values set in either notice/error or any user defined message in the controller can be accessed in the views to display the result of the action taken place in the controller.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Session in Ruby =&lt;br /&gt;
Most applications need to keep track of certain state of a particular user. Examples include shopping cart for online shopping account or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.&lt;br /&gt;
&lt;br /&gt;
A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client’s browser includes the session id. And the other way round, the browser will send it to the server on every request from the client. &lt;br /&gt;
&lt;br /&gt;
In Ruby session persists forever and is stored in the browser cookies by default. The session data can thus be deleted by clearing content of the cookies. Session is useful when we have to remember the state for  a long time. Examples include Authentication where the user enters its login id and password that needs to be available for the whole session that the user is logged in. There are some alternative storage modes for session such as Storage table or No SQL data structure.&amp;lt;ref name=&amp;quot;ref5&amp;quot;&amp;gt; http://www.tutorialspoint.com/ruby-on-rails/rails-session-cookies.htm/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= How it works =&lt;br /&gt;
&lt;br /&gt;
== Session  ==&lt;br /&gt;
Session stores small amount of data that persists between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms such as cookies, tables, cache, memcache etc.&lt;br /&gt;
The session stores session id in cookies as it is insecure when embedded in the url.This unique id is used to look up the session data on its storage locations such as cookies, database tables, no sql data structure, cache etc.The data storage in cookies by default makes the session lightweight and easy to access and it does not requires calls to the storage locations for accessing the session data. The cookies can store atmost 4 kb data and hence gives cookie overflow exception if the data in the session exceeds the 4 kb limit.The cookie data is not encrypted but it cannot be edited by being visible in the url. &amp;lt;ref name=&amp;quot;ref1&amp;quot;&amp;gt; http://guides.rubyonrails.org/security.html#sessions/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
Session values are stored in a key,value pair. In Ruby we store it like a hash.&lt;br /&gt;
&lt;br /&gt;
1. To add a session attribute we say &lt;br /&gt;
   session[:username]=params[:username]. &lt;br /&gt;
   Here we assign the username received from the user to the session variable.&lt;br /&gt;
2. To delete a session attribute value, just assign the key to nil.&lt;br /&gt;
   eg: session[:username]=nil. &lt;br /&gt;
   Here we are deleting the session attribute username.&lt;br /&gt;
3. The session can also be reset &lt;br /&gt;
   reset_session&lt;br /&gt;
   This will reset the complete session hash&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Flash is used by the controller to pass messages to the view. The controller can pass messages about the success or failure of the desired action. In Ruby,w e can also pass the flash message as part of the redirection again informing the view about the state of the action performed when redirecting. The user can also pass user defined messages and also pass messages for debugging purposes. The flash message displayed on the form/view is now taken care by the next request. The layout that receives the flash has to decide the action to be performed on the basis of the message received from the flash.&amp;lt;ref name=&amp;quot;ref4&amp;quot;&amp;gt;http://guides.rubyonrails.org/action_controller_overview.html#the-flash &amp;lt;/ref&amp;gt;&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. To set a  flash value as a notice &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
   flash[:notice]= &amp;quot;User logged in successfully&amp;quot; &lt;br /&gt;
   The flash message sets the notice value. This flashes the notice on the form when the user successfully logs into the system.  &lt;br /&gt;
&lt;br /&gt;
2. To set a flash value as a warning &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
    flash[:error]= &amp;quot;Please provide the username and password&amp;quot; &lt;br /&gt;
    The flash message sets the error value. This automatically flashes the notice saying that the user did not provide the username and password.  &lt;br /&gt;
&lt;br /&gt;
3. To set flash message as part of redirection&lt;br /&gt;
   redirect_to( posts_show,  :notice =&amp;gt; &amp;quot;Post successfully created&amp;quot; )&lt;br /&gt;
   The above statement redirects the method call to the appropriate url and displays a notice there automatically saying the post was successfully &lt;br /&gt;
   created.&lt;br /&gt;
&lt;br /&gt;
4. The value of flash to be saved for the subsequent requests&lt;br /&gt;
   flash.keep&lt;br /&gt;
   The above statement keeps all values of flash, that resulted from the redirection, to be used in the subsequent requests.&lt;br /&gt;
&lt;br /&gt;
5.  The value of flash to be saved in the current request &lt;br /&gt;
    flash.now&lt;br /&gt;
    The above statement keeps the values of flash, that resulted from the redirection, to be used for the current request.&lt;br /&gt;
&lt;br /&gt;
= Example - Session/Flash =&lt;br /&gt;
&lt;br /&gt;
:Class ExamplesController &amp;lt; ApplicationController&amp;lt;br&amp;gt;&lt;br /&gt;
::def index&lt;br /&gt;
::'''session[:example_name]=params[:example][:name]'''&lt;br /&gt;
::...&lt;br /&gt;
::end&lt;br /&gt;
::def update&lt;br /&gt;
:::@example = Example.find(params[:id])&lt;br /&gt;
:::respond_to do |format|&lt;br /&gt;
::::if @example.update_attributes(params[:type])&lt;br /&gt;
:::::format.html {redirect_to(@example, '''flash[:notice] =&amp;gt; 'Example was successfully updated.'''')}&lt;br /&gt;
::::else&lt;br /&gt;
:::::format.html { render :action =&amp;gt; &amp;quot;edit&amp;quot; }&lt;br /&gt;
::::end&lt;br /&gt;
:::end&lt;br /&gt;
::end&lt;br /&gt;
::def &lt;br /&gt;
::....&lt;br /&gt;
::end&lt;br /&gt;
:end&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''In the show(@example) view, we can make use of session and flash as- '''&lt;br /&gt;
&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;notice&amp;quot;&amp;gt;&amp;lt;%=notice%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;example name&amp;quot;&amp;gt;&amp;lt;%=session[:example_name]%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above code, the ExampleController class has a index method that sets the session for the user and &lt;br /&gt;
update method that sets the flash variable ,we set the session variable with the name of the example obtained from&lt;br /&gt;
the user stored in the params hash, we can access it in any view in that session.In the update method, flash is used to set&lt;br /&gt;
the notice to a desired value. Then it is used in the view  to display the message.&lt;br /&gt;
&lt;br /&gt;
= Advantages/Disadvantages =&lt;br /&gt;
&lt;br /&gt;
== Session &amp;lt;ref name=&amp;quot;ref6&amp;quot;&amp;gt; http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions_controller &amp;lt;/ref&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
'''Session Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 1.A session object helps us store useful information about the application like the session_id, currently logged in user details. &amp;lt;br&amp;gt;&lt;br /&gt;
 2.It is similar to hash and helps us take advantages of the hash functionalities in Ruby. &amp;lt;br&amp;gt;&lt;br /&gt;
 3.Since, it persists forever, the session variables can be used to perform authentication,server side validation and take care of the security aspects &lt;br /&gt;
   of the application. &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Session Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. The session object is a heavy weight object as it is used to store a lot of application related information.&amp;lt;br&amp;gt;&lt;br /&gt;
2. we have to be careful while dealing with session variables as it is subject to malicious attacks and sensitive information can be divulged if not &lt;br /&gt;
   taken care of while programming. &amp;lt;br&amp;gt;&lt;br /&gt;
3. As the session variables persists forever, it is the programmers responsibility to reset the information of the application when the application goes &lt;br /&gt;
   out of the current scope logically. &amp;lt;br&amp;gt;&lt;br /&gt;
4. Too many session variable manipulation and storage can make the code inefficient and can cause unexpected behaviour if not programmed carefully.&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&lt;br /&gt;
'''Flash Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. A lightweight object that helps us store the information of the state the application is in.&amp;lt;br&amp;gt;&lt;br /&gt;
2. Since flash is similar to hash, it helps us abuse the advantages of hash. &amp;lt;br&amp;gt;&lt;br /&gt;
3. Any key can be passed into the flash object and the user is responsible for extracting the information from the corresponding object &amp;lt;br&amp;gt;&lt;br /&gt;
4. It is less tedious to manage as its lifetime persists only until the next request.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. As the information stored in the flash object persists only until the next request, it is not useful for providing security related capabilities to &lt;br /&gt;
   the application.&amp;lt;br&amp;gt;&lt;br /&gt;
2. It has limited capabilities and used for displaying simple error messages, notices or warnings in the application.&amp;lt;br&amp;gt;&lt;br /&gt;
3. It cannot store dynamic information.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion/Summary =&lt;br /&gt;
&lt;br /&gt;
HTTP is a stateless protocol and the web applications require saving of the application state frequently. Based on the application state, certain actions are taken. This is possible in RUBY using redirection flash object. The redirection flash object persists for a short duration and helps us store simple information about the application. Another flash like object that provides us very rich capabilities in terms of information storge, authentication and security is the session object. We have seen the differences between the two. It is the programmers responsibility to appropriately use the flash or the session object depending on what needs to be achieved.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67228</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w67 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67228"/>
		<updated>2012-10-04T02:44:29Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;                                                            &lt;br /&gt;
= Overview/Introduction =&lt;br /&gt;
&amp;lt;p&amp;gt; Redirection in ruby refers to the where a user is redirected from one page to another. HTTP is stateless, hence session/flash makes it stateful.As the http requests are stateless, hence this leads to losing all the state that we had before. Thus Rails provides a hash called Flash such that it persists until the end of the next request received.&lt;br /&gt;
Also there is a session hash, which unlike flash persists forever. &amp;lt;ref&amp;gt;http://www.youtube.com/watch?v=0m8lmRwS7E0&amp;lt;/ref&amp;gt;.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p&amp;gt;For information on how to format the text of your article, create tables, and use section headings and references, see this [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/WIKI_Features article].&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Flash in Ruby =&lt;br /&gt;
&amp;lt;p&amp;gt;Flash in ruby helps to remember the state until the end of the next request. It is basically used to store error messages as warnings and information as notice in the hash. This is used in views to print the error messages or notice. Instead of notice or warnings, we can define user defined hash and print its value in the view as we did for the notice and warnings. Basically it helps in flashing messages on the views. It stores values in the form of hash table. It is particularly useful to show messages after a redirect.Whenever you want to display any kind of status message or error message &amp;quot;Your email id is updated&amp;quot; or &amp;quot;Invalid Password&amp;quot; etc.&lt;br /&gt;
Rails loads it when you set it in your controller code and it is displayed in your view (if you have it set to display in the view). Rails discards the value when it is rendered on the client. The Flash values set in either notice/error or any user defined message in the controller can be accessed in the views to display the result of the action taken place in the controller.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Session in Ruby =&lt;br /&gt;
Most applications need to keep track of certain state of a particular user. Examples include shopping cart for online shopping account or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.&lt;br /&gt;
&lt;br /&gt;
A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client’s browser includes the session id. And the other way round, the browser will send it to the server on every request from the client. &lt;br /&gt;
&lt;br /&gt;
In Ruby session persists forever and is stored in the browser cookies by default. The session data can thus be deleted by clearing content of the cookies. Session is useful when we have to remember the state for  a long time. Examples include Authentication where the user enters its login id and password that needs to be available for the whole session that the user is logged in. There are some alternative storage modes for session such as Storage table or No SQL data structure.&amp;lt;ref name=&amp;quot;ref5&amp;quot;&amp;gt; http://www.tutorialspoint.com/ruby-on-rails/rails-session-cookies.htm/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= How it works =&lt;br /&gt;
&lt;br /&gt;
== Session  ==&lt;br /&gt;
Session stores small amount of data that persists between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms such as cookies, tables, cache, memcache etc.&lt;br /&gt;
The session stores session id in cookies as it is insecure when embedded in the url.This unique id is used to look up the session data on its storage locations such as cookies, database tables, no sql data structure, cache etc.The data storage in cookies by default makes the session lightweight and easy to access and it does not requires calls to the storage locations for accessing the session data. The cookies can store atmost 4 kb data and hence gives cookie overflow exception if the data in the session exceeds the 4 kb limit.The cookie data is not encrypted but it cannot be edited by being visible in the url. &amp;lt;ref name=&amp;quot;ref1&amp;quot;&amp;gt; http://guides.rubyonrails.org/security.html#sessions/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
Session values are stored in a key,value pair. In Ruby we store it like a hash.&lt;br /&gt;
&lt;br /&gt;
1. To add a session attribute we say &lt;br /&gt;
   session[:username]=params[:username]. &lt;br /&gt;
   Here we assign the username received from the user to the session variable.&lt;br /&gt;
2. To delete a session attribute value, just assign the key to nil.&lt;br /&gt;
   eg: session[:username]=nil. &lt;br /&gt;
   Here we are deleting the session attribute username.&lt;br /&gt;
3. The session can also be reset &lt;br /&gt;
   reset_session&lt;br /&gt;
   This will reset the complete session hash&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Flash is used by the controller to pass messages to the view. The controller can pass messages about the success or failure of the desired action. In Ruby,w e can also pass the flash message as part of the redirection again informing the view about the state of the action performed when redirecting. The user can also pass user defined messages and also pass messages for debugging purposes. The flash message displayed on the form/view is now taken care by the next request. The layout that receives the flash has to decide the action to be performed on the basis of the message received from the flash.&amp;lt;ref name=&amp;quot;ref4&amp;quot;&amp;gt;http://guides.rubyonrails.org/action_controller_overview.html#the-flash &amp;lt;/ref&amp;gt;&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. To set a  flash value as a notice &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
   flash[:notice]= &amp;quot;User logged in successfully&amp;quot; &lt;br /&gt;
   The flash message sets the notice value. This flashes the notice on the form when the user successfully logs into the system.  &lt;br /&gt;
&lt;br /&gt;
2. To set a flash value as a warning &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
    flash[:error]= &amp;quot;Please provide the username and password&amp;quot; &lt;br /&gt;
    The flash message sets the error value. This automatically flashes the notice saying that the user did not provide the username and password.  &lt;br /&gt;
&lt;br /&gt;
3. To set flash message as part of redirection&lt;br /&gt;
   redirect_to( posts_show,  :notice =&amp;gt; &amp;quot;Post successfully created&amp;quot; )&lt;br /&gt;
   The above statement redirects the method call to the appropriate url and displays a notice there automatically saying the post was successfully &lt;br /&gt;
   created.&lt;br /&gt;
&lt;br /&gt;
4. The value of flash to be saved for the subsequent requests&lt;br /&gt;
   flash.keep&lt;br /&gt;
   The above statement keeps all values of flash, that resulted from the redirection, to be used in the subsequent requests.&lt;br /&gt;
&lt;br /&gt;
5.  The value of flash to be saved in the current request &lt;br /&gt;
    flash.now&lt;br /&gt;
    The above statement keeps the values of flash, that resulted from the redirection, to be used for the current request.&lt;br /&gt;
&lt;br /&gt;
= Example - Session/Flash =&lt;br /&gt;
&lt;br /&gt;
:Class ExamplesController &amp;lt; ApplicationController&amp;lt;br&amp;gt;&lt;br /&gt;
::def index&lt;br /&gt;
::'''session[:example_name]=params[:example][:name]'''&lt;br /&gt;
::...&lt;br /&gt;
::end&lt;br /&gt;
::def update&lt;br /&gt;
:::@example = Example.find(params[:id])&lt;br /&gt;
:::respond_to do |format|&lt;br /&gt;
::::if @example.update_attributes(params[:type])&lt;br /&gt;
:::::format.html {redirect_to(@example, '''flash[:notice] =&amp;gt; 'Example was successfully updated.'''')}&lt;br /&gt;
::::else&lt;br /&gt;
:::::format.html { render :action =&amp;gt; &amp;quot;edit&amp;quot; }&lt;br /&gt;
::::end&lt;br /&gt;
:::end&lt;br /&gt;
::end&lt;br /&gt;
::def &lt;br /&gt;
::....&lt;br /&gt;
::end&lt;br /&gt;
:end&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''In the show(@example) view, we can make use of session and flash as- '''&lt;br /&gt;
&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;notice&amp;quot;&amp;gt;&amp;lt;%=notice%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;example name&amp;quot;&amp;gt;&amp;lt;%=session[:example_name]%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above code, the ExampleController class has a index method that sets the session for the user and &lt;br /&gt;
update method that sets the flash variable ,we set the session variable with the name of the example obtained from&lt;br /&gt;
the user stored in the params hash, we can access it in any view in that session.In the update method, flash is used to set&lt;br /&gt;
the notice to a desired value. Then it is used in the view  to display the message.&lt;br /&gt;
&lt;br /&gt;
= Advantages/Disadvantages =&lt;br /&gt;
&lt;br /&gt;
== Session &amp;lt;ref name=&amp;quot;ref6&amp;quot;&amp;gt; http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions_controller &amp;lt;/ref&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
'''Session Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 1.A session object helps us store useful information about the application like the session_id, currently logged in user details. &amp;lt;br&amp;gt;&lt;br /&gt;
 2.It is similar to hash and helps us take advantages of the hash functionalities in Ruby. &amp;lt;br&amp;gt;&lt;br /&gt;
 3.Since, it persists forever, the session variables can be used to perform authentication,server side validation and take care of the security aspects &lt;br /&gt;
   of the application. &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Session Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. The session object is a heavy weight object as it is used to store a lot of application related information.&amp;lt;br&amp;gt;&lt;br /&gt;
2. we have to be careful while dealing with session variables as it is subject to malicious attacks and sensitive information can be divulged if not &lt;br /&gt;
   taken care of while programming. &amp;lt;br&amp;gt;&lt;br /&gt;
3. As the session variables persists forever, it is the programmers responsibility to reset the information of the application when the application goes &lt;br /&gt;
   out of the current scope logically. &amp;lt;br&amp;gt;&lt;br /&gt;
4. Too many session variable manipulation and storage can make the code inefficient and can cause unexpected behaviour if not programmed carefully.&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&lt;br /&gt;
'''Flash Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. A lightweight object that helps us store the information of the state the application is in.&amp;lt;br&amp;gt;&lt;br /&gt;
2. Since flash is similar to hash, it helps us abuse the advantages of hash. &amp;lt;br&amp;gt;&lt;br /&gt;
3. Any key can be passed into the flash object and the user is responsible for extracting the information from the corresponding object &amp;lt;br&amp;gt;&lt;br /&gt;
4. It is less tedious to manage as its lifetime persists only until the next request.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. As the information stored in the flash object persists only until the next request, it is not useful for providing security related capabilities to &lt;br /&gt;
   the application.&amp;lt;br&amp;gt;&lt;br /&gt;
2. It has limited capabilities and used for displaying simple error messages, notices or warnings in the application.&amp;lt;br&amp;gt;&lt;br /&gt;
3. It cannot store dynamic information.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion/Summary =&lt;br /&gt;
&lt;br /&gt;
HTTP is a stateless protocol and the web applications require saving of the application state frequently. Based on the application state, certain actions are taken. This is possible in RUBY using redirection flash object. The redirection flash object persists for a short duration and helps us store simple information about the application. Another flash like object that provides us very rich capabilities in terms of information storge, authentication and security is the session object. We have seen the differences between the two. It is the programmers responsibility to appropriately use the flash or the session object depending on what needs to be achieved.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67227</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w67 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67227"/>
		<updated>2012-10-04T02:44:12Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Session */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;                                                            &lt;br /&gt;
= Overview/Introduction =&lt;br /&gt;
&amp;lt;p&amp;gt; Redirection in ruby refers to the where a user is redirected from one page to another. HTTP is stateless, hence session/flash makes it stateful.As the http requests are stateless, hence this leads to losing all the state that we had before. Thus Rails provides a hash called Flash such that it persists until the end of the next request received.&lt;br /&gt;
Also there is a session hash, which unlike flash persists forever. &amp;lt;ref&amp;gt;http://www.youtube.com/watch?v=0m8lmRwS7E0&amp;lt;/ref&amp;gt;.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p&amp;gt;For information on how to format the text of your article, create tables, and use section headings and references, see this [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/WIKI_Features article].&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Flash in Ruby =&lt;br /&gt;
&amp;lt;p&amp;gt;Flash in ruby helps to remember the state until the end of the next request. It is basically used to store error messages as warnings and information as notice in the hash. This is used in views to print the error messages or notice. Instead of notice or warnings, we can define user defined hash and print its value in the view as we did for the notice and warnings. Basically it helps in flashing messages on the views. It stores values in the form of hash table. It is particularly useful to show messages after a redirect.Whenever you want to display any kind of status message or error message &amp;quot;Your email id is updated&amp;quot; or &amp;quot;Invalid Password&amp;quot; etc.&lt;br /&gt;
Rails loads it when you set it in your controller code and it is displayed in your view (if you have it set to display in the view). Rails discards the value when it is rendered on the client. The Flash values set in either notice/error or any user defined message in the controller can be accessed in the views to display the result of the action taken place in the controller.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Session in Ruby =&lt;br /&gt;
Most applications need to keep track of certain state of a particular user. Examples include shopping cart for online shopping account or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.&lt;br /&gt;
&lt;br /&gt;
A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client’s browser includes the session id. And the other way round, the browser will send it to the server on every request from the client. &lt;br /&gt;
&lt;br /&gt;
In Ruby session persists forever and is stored in the browser cookies by default. The session data can thus be deleted by clearing content of the cookies. Session is useful when we have to remember the state for  a long time. Examples include Authentication where the user enters its login id and password that needs to be available for the whole session that the user is logged in. There are some alternative storage modes for session such as Storage table or No SQL data structure.&amp;lt;ref name=&amp;quot;ref5&amp;quot;&amp;gt; http://www.tutorialspoint.com/ruby-on-rails/rails-session-cookies.htm/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= How it works =&lt;br /&gt;
&lt;br /&gt;
== Session  ==&lt;br /&gt;
Session stores small amount of data that persists between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms such as cookies, tables, cache, memcache etc.&lt;br /&gt;
The session stores session id in cookies as it is insecure when embedded in the url.This unique id is used to look up the session data on its storage locations such as cookies, database tables, no sql data structure, cache etc.The data storage in cookies by default makes the session lightweight and easy to access and it does not requires calls to the storage locations for accessing the session data. The cookies can store atmost 4 kb data and hence gives cookie overflow exception if the data in the session exceeds the 4 kb limit.The cookie data is not encrypted but it cannot be edited by being visible in the url. &amp;lt;ref name=&amp;quot;ref1&amp;quot;&amp;gt; http://guides.rubyonrails.org/security.html#sessions/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
Session values are stored in a key,value pair. In Ruby we store it like a hash.&lt;br /&gt;
&lt;br /&gt;
1. To add a session attribute we say &lt;br /&gt;
   session[:username]=params[:username]. &lt;br /&gt;
   Here we assign the username received from the user to the session variable.&lt;br /&gt;
2. To delete a session attribute value, just assign the key to nil.&lt;br /&gt;
   eg: session[:username]=nil. &lt;br /&gt;
   Here we are deleting the session attribute username.&lt;br /&gt;
3. The session can also be reset &lt;br /&gt;
   reset_session&lt;br /&gt;
   This will reset the complete session hash&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Flash is used by the controller to pass messages to the view. The controller can pass messages about the success or failure of the desired action. In Ruby,w e can also pass the flash message as part of the redirection again informing the view about the state of the action performed when redirecting. The user can also pass user defined messages and also pass messages for debugging purposes. The flash message displayed on the form/view is now taken care by the next request. The layout that receives the flash has to decide the action to be performed on the basis of the message received from the flash.&amp;lt;ref name=&amp;quot;ref4&amp;quot;&amp;gt;http://guides.rubyonrails.org/action_controller_overview.html#the-flash &amp;lt;/ref&amp;gt;&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. To set a  flash value as a notice &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
   flash[:notice]= &amp;quot;User logged in successfully&amp;quot; &lt;br /&gt;
   The flash message sets the notice value. This flashes the notice on the form when the user successfully logs into the system.  &lt;br /&gt;
&lt;br /&gt;
2. To set a flash value as a warning &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
    flash[:error]= &amp;quot;Please provide the username and password&amp;quot; &lt;br /&gt;
    The flash message sets the error value. This automatically flashes the notice saying that the user did not provide the username and password.  &lt;br /&gt;
&lt;br /&gt;
3. To set flash message as part of redirection&lt;br /&gt;
   redirect_to( posts_show,  :notice =&amp;gt; &amp;quot;Post successfully created&amp;quot; )&lt;br /&gt;
   The above statement redirects the method call to the appropriate url and displays a notice there automatically saying the post was successfully &lt;br /&gt;
   created.&lt;br /&gt;
&lt;br /&gt;
4. The value of flash to be saved for the subsequent requests&lt;br /&gt;
   flash.keep&lt;br /&gt;
   The above statement keeps all values of flash, that resulted from the redirection, to be used in the subsequent requests.&lt;br /&gt;
&lt;br /&gt;
5.  The value of flash to be saved in the current request &lt;br /&gt;
    flash.now&lt;br /&gt;
    The above statement keeps the values of flash, that resulted from the redirection, to be used for the current request.&lt;br /&gt;
&lt;br /&gt;
= Example - Session/Flash =&lt;br /&gt;
&lt;br /&gt;
:Class ExamplesController &amp;lt; ApplicationController&amp;lt;br&amp;gt;&lt;br /&gt;
::def index&lt;br /&gt;
::'''session[:example_name]=params[:example][:name]'''&lt;br /&gt;
::...&lt;br /&gt;
::end&lt;br /&gt;
::def update&lt;br /&gt;
:::@example = Example.find(params[:id])&lt;br /&gt;
:::respond_to do |format|&lt;br /&gt;
::::if @example.update_attributes(params[:type])&lt;br /&gt;
:::::format.html {redirect_to(@example, '''flash[:notice] =&amp;gt; 'Example was successfully updated.'''')}&lt;br /&gt;
::::else&lt;br /&gt;
:::::format.html { render :action =&amp;gt; &amp;quot;edit&amp;quot; }&lt;br /&gt;
::::end&lt;br /&gt;
:::end&lt;br /&gt;
::end&lt;br /&gt;
::def &lt;br /&gt;
::....&lt;br /&gt;
::end&lt;br /&gt;
:end&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''In the show(@example) view, we can make use of session and flash as- '''&lt;br /&gt;
&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;notice&amp;quot;&amp;gt;&amp;lt;%=notice%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;example name&amp;quot;&amp;gt;&amp;lt;%=session[:example_name]%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above code, the ExampleController class has a index method that sets the session for the user and &lt;br /&gt;
update method that sets the flash variable ,we set the session variable with the name of the example obtained from&lt;br /&gt;
the user stored in the params hash, we can access it in any view in that session.In the update method, flash is used to set&lt;br /&gt;
the notice to a desired value. Then it is used in the view  to display the message.&lt;br /&gt;
&lt;br /&gt;
= Advantages/Disadvantages =&lt;br /&gt;
&lt;br /&gt;
== Session &amp;lt;ref name=&amp;quot;ref6&amp;quot;&amp;gt; http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions_controller &amp;lt;/ref&amp;gt; ==&lt;br /&gt;
&lt;br /&gt;
'''Session Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 1.A session object helps us store useful information about the application like the session_id, currently logged in user details. &amp;lt;br&amp;gt;&lt;br /&gt;
 2.It is similar to hash and helps us take advantages of the hash functionalities in Ruby. &amp;lt;br&amp;gt;&lt;br /&gt;
 3.Since, it persists forever, the session variables can be used to perform authentication,server side validation and take care of the security aspects &lt;br /&gt;
   of the application. &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Session Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. The session object is a heavy weight object as it is used to store a lot of application related information.&amp;lt;br&amp;gt;&lt;br /&gt;
2. we have to be careful while dealing with session variables as it is subject to malicious attacks and sensitive information can be divulged if not &lt;br /&gt;
   taken care of while programming. &amp;lt;br&amp;gt;&lt;br /&gt;
3. As the session variables persists forever, it is the programmers responsibility to reset the information of the application when the application goes &lt;br /&gt;
   out of the current scope logically. &amp;lt;br&amp;gt;&lt;br /&gt;
4. Too many session variable manipulation and storage can make the code inefficient and can cause unexpected behaviour if not programmed carefully.&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&lt;br /&gt;
'''Flash Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. A lightweight object that helps us store the information of the state the application is in.&amp;lt;br&amp;gt;&lt;br /&gt;
2. Since flash is similar to hash, it helps us abuse the advantages of hash. &amp;lt;br&amp;gt;&lt;br /&gt;
3. Any key can be passed into the flash object and the user is responsible for extracting the information from the corresponding object &amp;lt;br&amp;gt;&lt;br /&gt;
4. It is less tedious to manage as its lifetime persists only until the next request.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. As the information stored in the flash object persists only until the next request, it is not useful for providing security related capabilities to &lt;br /&gt;
   the application.&amp;lt;br&amp;gt;&lt;br /&gt;
2. It has limited capabilities and used for displaying simple error messages, notices or warnings in the application.&amp;lt;br&amp;gt;&lt;br /&gt;
3. It cannot store dynamic information.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion/Summary =&lt;br /&gt;
&lt;br /&gt;
HTTP is a stateless protocol and the web applications require saving of the application state frequently. Based on the application state, certain actions are taken. This is possible in RUBY using redirection flash object. The redirection flash object persists for a short duration and helps us store simple information about the application. Another flash like object that provides us very rich capabilities in terms of information storge, authentication and security is the session object. We have seen the differences between the two. It is the programmers responsibility to appropriately use the flash or the session object depending on what needs to be achieved.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions_controller&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67224</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w67 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67224"/>
		<updated>2012-10-04T02:42:59Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;                                                            &lt;br /&gt;
= Overview/Introduction =&lt;br /&gt;
&amp;lt;p&amp;gt; Redirection in ruby refers to the where a user is redirected from one page to another. HTTP is stateless, hence session/flash makes it stateful.As the http requests are stateless, hence this leads to losing all the state that we had before. Thus Rails provides a hash called Flash such that it persists until the end of the next request received.&lt;br /&gt;
Also there is a session hash, which unlike flash persists forever. &amp;lt;ref&amp;gt;http://www.youtube.com/watch?v=0m8lmRwS7E0&amp;lt;/ref&amp;gt;.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p&amp;gt;For information on how to format the text of your article, create tables, and use section headings and references, see this [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/WIKI_Features article].&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Flash in Ruby =&lt;br /&gt;
&amp;lt;p&amp;gt;Flash in ruby helps to remember the state until the end of the next request. It is basically used to store error messages as warnings and information as notice in the hash. This is used in views to print the error messages or notice. Instead of notice or warnings, we can define user defined hash and print its value in the view as we did for the notice and warnings. Basically it helps in flashing messages on the views. It stores values in the form of hash table. It is particularly useful to show messages after a redirect.Whenever you want to display any kind of status message or error message &amp;quot;Your email id is updated&amp;quot; or &amp;quot;Invalid Password&amp;quot; etc.&lt;br /&gt;
Rails loads it when you set it in your controller code and it is displayed in your view (if you have it set to display in the view). Rails discards the value when it is rendered on the client. The Flash values set in either notice/error or any user defined message in the controller can be accessed in the views to display the result of the action taken place in the controller.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Session in Ruby =&lt;br /&gt;
Most applications need to keep track of certain state of a particular user. Examples include shopping cart for online shopping account or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.&lt;br /&gt;
&lt;br /&gt;
A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client’s browser includes the session id. And the other way round, the browser will send it to the server on every request from the client. &lt;br /&gt;
&lt;br /&gt;
In Ruby session persists forever and is stored in the browser cookies by default. The session data can thus be deleted by clearing content of the cookies. Session is useful when we have to remember the state for  a long time. Examples include Authentication where the user enters its login id and password that needs to be available for the whole session that the user is logged in. There are some alternative storage modes for session such as Storage table or No SQL data structure.&amp;lt;ref name=&amp;quot;ref5&amp;quot;&amp;gt; http://www.tutorialspoint.com/ruby-on-rails/rails-session-cookies.htm/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= How it works =&lt;br /&gt;
&lt;br /&gt;
== Session  ==&lt;br /&gt;
Session stores small amount of data that persists between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms such as cookies, tables, cache, memcache etc.&lt;br /&gt;
The session stores session id in cookies as it is insecure when embedded in the url.This unique id is used to look up the session data on its storage locations such as cookies, database tables, no sql data structure, cache etc.The data storage in cookies by default makes the session lightweight and easy to access and it does not requires calls to the storage locations for accessing the session data. The cookies can store atmost 4 kb data and hence gives cookie overflow exception if the data in the session exceeds the 4 kb limit.The cookie data is not encrypted but it cannot be edited by being visible in the url. &amp;lt;ref name=&amp;quot;ref1&amp;quot;&amp;gt; http://guides.rubyonrails.org/security.html#sessions/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
Session values are stored in a key,value pair. In Ruby we store it like a hash.&lt;br /&gt;
&lt;br /&gt;
1. To add a session attribute we say &lt;br /&gt;
   session[:username]=params[:username]. &lt;br /&gt;
   Here we assign the username received from the user to the session variable.&lt;br /&gt;
2. To delete a session attribute value, just assign the key to nil.&lt;br /&gt;
   eg: session[:username]=nil. &lt;br /&gt;
   Here we are deleting the session attribute username.&lt;br /&gt;
3. The session can also be reset &lt;br /&gt;
   reset_session&lt;br /&gt;
   This will reset the complete session hash&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Flash is used by the controller to pass messages to the view. The controller can pass messages about the success or failure of the desired action. In Ruby,w e can also pass the flash message as part of the redirection again informing the view about the state of the action performed when redirecting. The user can also pass user defined messages and also pass messages for debugging purposes. The flash message displayed on the form/view is now taken care by the next request. The layout that receives the flash has to decide the action to be performed on the basis of the message received from the flash.&amp;lt;ref name=&amp;quot;ref4&amp;quot;&amp;gt;http://guides.rubyonrails.org/action_controller_overview.html#the-flash &amp;lt;/ref&amp;gt;&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. To set a  flash value as a notice &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
   flash[:notice]= &amp;quot;User logged in successfully&amp;quot; &lt;br /&gt;
   The flash message sets the notice value. This flashes the notice on the form when the user successfully logs into the system.  &lt;br /&gt;
&lt;br /&gt;
2. To set a flash value as a warning &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
    flash[:error]= &amp;quot;Please provide the username and password&amp;quot; &lt;br /&gt;
    The flash message sets the error value. This automatically flashes the notice saying that the user did not provide the username and password.  &lt;br /&gt;
&lt;br /&gt;
3. To set flash message as part of redirection&lt;br /&gt;
   redirect_to( posts_show,  :notice =&amp;gt; &amp;quot;Post successfully created&amp;quot; )&lt;br /&gt;
   The above statement redirects the method call to the appropriate url and displays a notice there automatically saying the post was successfully &lt;br /&gt;
   created.&lt;br /&gt;
&lt;br /&gt;
4. The value of flash to be saved for the subsequent requests&lt;br /&gt;
   flash.keep&lt;br /&gt;
   The above statement keeps all values of flash, that resulted from the redirection, to be used in the subsequent requests.&lt;br /&gt;
&lt;br /&gt;
5.  The value of flash to be saved in the current request &lt;br /&gt;
    flash.now&lt;br /&gt;
    The above statement keeps the values of flash, that resulted from the redirection, to be used for the current request.&lt;br /&gt;
&lt;br /&gt;
= Example - Session/Flash =&lt;br /&gt;
&lt;br /&gt;
:Class ExamplesController &amp;lt; ApplicationController&amp;lt;br&amp;gt;&lt;br /&gt;
::def index&lt;br /&gt;
::'''session[:example_name]=params[:example][:name]'''&lt;br /&gt;
::...&lt;br /&gt;
::end&lt;br /&gt;
::def update&lt;br /&gt;
:::@example = Example.find(params[:id])&lt;br /&gt;
:::respond_to do |format|&lt;br /&gt;
::::if @example.update_attributes(params[:type])&lt;br /&gt;
:::::format.html {redirect_to(@example, '''flash[:notice] =&amp;gt; 'Example was successfully updated.'''')}&lt;br /&gt;
::::else&lt;br /&gt;
:::::format.html { render :action =&amp;gt; &amp;quot;edit&amp;quot; }&lt;br /&gt;
::::end&lt;br /&gt;
:::end&lt;br /&gt;
::end&lt;br /&gt;
::def &lt;br /&gt;
::....&lt;br /&gt;
::end&lt;br /&gt;
:end&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''In the show(@example) view, we can make use of session and flash as- '''&lt;br /&gt;
&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;notice&amp;quot;&amp;gt;&amp;lt;%=notice%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;example name&amp;quot;&amp;gt;&amp;lt;%=session[:example_name]%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above code, the ExampleController class has a index method that sets the session for the user and &lt;br /&gt;
update method that sets the flash variable ,we set the session variable with the name of the example obtained from&lt;br /&gt;
the user stored in the params hash, we can access it in any view in that session.In the update method, flash is used to set&lt;br /&gt;
the notice to a desired value. Then it is used in the view  to display the message.&lt;br /&gt;
&lt;br /&gt;
= Advantages/Disadvantages =&lt;br /&gt;
&lt;br /&gt;
== Session ==&lt;br /&gt;
&lt;br /&gt;
'''Session Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 1.A session object helps us store useful information about the application like the session_id, currently logged in user details. &amp;lt;br&amp;gt;&lt;br /&gt;
 2.It is similar to hash and helps us take advantages of the hash functionalities in Ruby. &amp;lt;br&amp;gt;&lt;br /&gt;
 3.Since, it persists forever, the session variables can be used to perform authentication,server side validation and take care of the security aspects &lt;br /&gt;
   of the application. &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Session Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. The session object is a heavy weight object as it is used to store a lot of application related information.&amp;lt;br&amp;gt;&lt;br /&gt;
2. we have to be careful while dealing with session variables as it is subject to malicious attacks and sensitive information can be divulged if not &lt;br /&gt;
   taken care of while programming. &amp;lt;br&amp;gt;&lt;br /&gt;
3. As the session variables persists forever, it is the programmers responsibility to reset the information of the application when the application goes &lt;br /&gt;
   out of the current scope logically. &amp;lt;br&amp;gt;&lt;br /&gt;
4. Too many session variable manipulation and storage can make the code inefficient and can cause unexpected behaviour if not programmed carefully.&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&lt;br /&gt;
'''Flash Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. A lightweight object that helps us store the information of the state the application is in.&amp;lt;br&amp;gt;&lt;br /&gt;
2. Since flash is similar to hash, it helps us abuse the advantages of hash. &amp;lt;br&amp;gt;&lt;br /&gt;
3. Any key can be passed into the flash object and the user is responsible for extracting the information from the corresponding object &amp;lt;br&amp;gt;&lt;br /&gt;
4. It is less tedious to manage as its lifetime persists only until the next request.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. As the information stored in the flash object persists only until the next request, it is not useful for providing security related capabilities to &lt;br /&gt;
   the application.&amp;lt;br&amp;gt;&lt;br /&gt;
2. It has limited capabilities and used for displaying simple error messages, notices or warnings in the application.&amp;lt;br&amp;gt;&lt;br /&gt;
3. It cannot store dynamic information.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion/Summary =&lt;br /&gt;
&lt;br /&gt;
HTTP is a stateless protocol and the web applications require saving of the application state frequently. Based on the application state, certain actions are taken. This is possible in RUBY using redirection flash object. The redirection flash object persists for a short duration and helps us store simple information about the application. Another flash like object that provides us very rich capabilities in terms of information storge, authentication and security is the session object. We have seen the differences between the two. It is the programmers responsibility to appropriately use the flash or the session object depending on what needs to be achieved.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions_controller&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67223</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w67 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67223"/>
		<updated>2012-10-04T02:42:43Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Session in Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;                                                            &lt;br /&gt;
= Overview/Introduction =&lt;br /&gt;
&amp;lt;p&amp;gt; Redirection in ruby refers to the where a user is redirected from one page to another. HTTP is stateless, hence session/flash makes it stateful.As the http requests are stateless, hence this leads to losing all the state that we had before. Thus Rails provides a hash called Flash such that it persists until the end of the next request received.&lt;br /&gt;
Also there is a session hash, which unlike flash persists forever. &amp;lt;ref&amp;gt;http://www.youtube.com/watch?v=0m8lmRwS7E0&amp;lt;/ref&amp;gt;.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p&amp;gt;For information on how to format the text of your article, create tables, and use section headings and references, see this [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/WIKI_Features article].&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Flash in Ruby =&lt;br /&gt;
&amp;lt;p&amp;gt;Flash in ruby helps to remember the state until the end of the next request. It is basically used to store error messages as warnings and information as notice in the hash. This is used in views to print the error messages or notice. Instead of notice or warnings, we can define user defined hash and print its value in the view as we did for the notice and warnings. Basically it helps in flashing messages on the views. It stores values in the form of hash table. It is particularly useful to show messages after a redirect.Whenever you want to display any kind of status message or error message &amp;quot;Your email id is updated&amp;quot; or &amp;quot;Invalid Password&amp;quot; etc.&lt;br /&gt;
Rails loads it when you set it in your controller code and it is displayed in your view (if you have it set to display in the view). Rails discards the value when it is rendered on the client. The Flash values set in either notice/error or any user defined message in the controller can be accessed in the views to display the result of the action taken place in the controller.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Session in Ruby =&lt;br /&gt;
Most applications need to keep track of certain state of a particular user. Examples include shopping cart for online shopping account or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.&lt;br /&gt;
&lt;br /&gt;
A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client’s browser includes the session id. And the other way round, the browser will send it to the server on every request from the client. &lt;br /&gt;
&lt;br /&gt;
In Ruby session persists forever and is stored in the browser cookies by default. The session data can thus be deleted by clearing content of the cookies. Session is useful when we have to remember the state for  a long time. Examples include Authentication where the user enters its login id and password that needs to be available for the whole session that the user is logged in. There are some alternative storage modes for session such as Storage table or No SQL data structure.&amp;lt;ref name=&amp;quot;ref5&amp;quot;&amp;gt; http://www.tutorialspoint.com/ruby-on-rails/rails-session-cookies.htm/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= How it works =&lt;br /&gt;
&lt;br /&gt;
== Session  ==&lt;br /&gt;
Session stores small amount of data that persists between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms such as cookies, tables, cache, memcache etc.&lt;br /&gt;
The session stores session id in cookies as it is insecure when embedded in the url.This unique id is used to look up the session data on its storage locations such as cookies, database tables, no sql data structure, cache etc.The data storage in cookies by default makes the session lightweight and easy to access and it does not requires calls to the storage locations for accessing the session data. The cookies can store atmost 4 kb data and hence gives cookie overflow exception if the data in the session exceeds the 4 kb limit.The cookie data is not encrypted but it cannot be edited by being visible in the url. &amp;lt;ref name=&amp;quot;ref1&amp;quot;&amp;gt; http://guides.rubyonrails.org/security.html#sessions/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
Session values are stored in a key,value pair. In Ruby we store it like a hash.&lt;br /&gt;
&lt;br /&gt;
1. To add a session attribute we say &lt;br /&gt;
   session[:username]=params[:username]. &lt;br /&gt;
   Here we assign the username received from the user to the session variable.&lt;br /&gt;
2. To delete a session attribute value, just assign the key to nil.&lt;br /&gt;
   eg: session[:username]=nil. &lt;br /&gt;
   Here we are deleting the session attribute username.&lt;br /&gt;
3. The session can also be reset &lt;br /&gt;
   reset_session&lt;br /&gt;
   This will reset the complete session hash&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Flash is used by the controller to pass messages to the view. The controller can pass messages about the success or failure of the desired action. In Ruby,w e can also pass the flash message as part of the redirection again informing the view about the state of the action performed when redirecting. The user can also pass user defined messages and also pass messages for debugging purposes. The flash message displayed on the form/view is now taken care by the next request. The layout that receives the flash has to decide the action to be performed on the basis of the message received from the flash.&amp;lt;ref name=&amp;quot;ref4&amp;quot;&amp;gt;http://guides.rubyonrails.org/action_controller_overview.html#the-flash &amp;lt;/ref&amp;gt;&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. To set a  flash value as a notice &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
   flash[:notice]= &amp;quot;User logged in successfully&amp;quot; &lt;br /&gt;
   The flash message sets the notice value. This flashes the notice on the form when the user successfully logs into the system.  &lt;br /&gt;
&lt;br /&gt;
2. To set a flash value as a warning &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
    flash[:error]= &amp;quot;Please provide the username and password&amp;quot; &lt;br /&gt;
    The flash message sets the error value. This automatically flashes the notice saying that the user did not provide the username and password.  &lt;br /&gt;
&lt;br /&gt;
3. To set flash message as part of redirection&lt;br /&gt;
   redirect_to( posts_show,  :notice =&amp;gt; &amp;quot;Post successfully created&amp;quot; )&lt;br /&gt;
   The above statement redirects the method call to the appropriate url and displays a notice there automatically saying the post was successfully &lt;br /&gt;
   created.&lt;br /&gt;
&lt;br /&gt;
4. The value of flash to be saved for the subsequent requests&lt;br /&gt;
   flash.keep&lt;br /&gt;
   The above statement keeps all values of flash, that resulted from the redirection, to be used in the subsequent requests.&lt;br /&gt;
&lt;br /&gt;
5.  The value of flash to be saved in the current request &lt;br /&gt;
    flash.now&lt;br /&gt;
    The above statement keeps the values of flash, that resulted from the redirection, to be used for the current request.&lt;br /&gt;
&lt;br /&gt;
= Example - Session/Flash =&lt;br /&gt;
&lt;br /&gt;
:Class ExamplesController &amp;lt; ApplicationController&amp;lt;br&amp;gt;&lt;br /&gt;
::def index&lt;br /&gt;
::'''session[:example_name]=params[:example][:name]'''&lt;br /&gt;
::...&lt;br /&gt;
::end&lt;br /&gt;
::def update&lt;br /&gt;
:::@example = Example.find(params[:id])&lt;br /&gt;
:::respond_to do |format|&lt;br /&gt;
::::if @example.update_attributes(params[:type])&lt;br /&gt;
:::::format.html {redirect_to(@example, '''flash[:notice] =&amp;gt; 'Example was successfully updated.'''')}&lt;br /&gt;
::::else&lt;br /&gt;
:::::format.html { render :action =&amp;gt; &amp;quot;edit&amp;quot; }&lt;br /&gt;
::::end&lt;br /&gt;
:::end&lt;br /&gt;
::end&lt;br /&gt;
::def &lt;br /&gt;
::....&lt;br /&gt;
::end&lt;br /&gt;
:end&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''In the show(@example) view, we can make use of session and flash as- '''&lt;br /&gt;
&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;notice&amp;quot;&amp;gt;&amp;lt;%=notice%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;example name&amp;quot;&amp;gt;&amp;lt;%=session[:example_name]%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above code, the ExampleController class has a index method that sets the session for the user and &lt;br /&gt;
update method that sets the flash variable ,we set the session variable with the name of the example obtained from&lt;br /&gt;
the user stored in the params hash, we can access it in any view in that session.In the update method, flash is used to set&lt;br /&gt;
the notice to a desired value. Then it is used in the view  to display the message.&lt;br /&gt;
&lt;br /&gt;
= Advantages/Disadvantages =&lt;br /&gt;
&lt;br /&gt;
== Session ==&lt;br /&gt;
&lt;br /&gt;
'''Session Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 1.A session object helps us store useful information about the application like the session_id, currently logged in user details. &amp;lt;br&amp;gt;&lt;br /&gt;
 2.It is similar to hash and helps us take advantages of the hash functionalities in Ruby. &amp;lt;br&amp;gt;&lt;br /&gt;
 3.Since, it persists forever, the session variables can be used to perform authentication,server side validation and take care of the security aspects &lt;br /&gt;
   of the application. &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Session Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. The session object is a heavy weight object as it is used to store a lot of application related information.&amp;lt;br&amp;gt;&lt;br /&gt;
2. we have to be careful while dealing with session variables as it is subject to malicious attacks and sensitive information can be divulged if not &lt;br /&gt;
   taken care of while programming. &amp;lt;br&amp;gt;&lt;br /&gt;
3. As the session variables persists forever, it is the programmers responsibility to reset the information of the application when the application goes &lt;br /&gt;
   out of the current scope logically. &amp;lt;br&amp;gt;&lt;br /&gt;
4. Too many session variable manipulation and storage can make the code inefficient and can cause unexpected behaviour if not programmed carefully.&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&lt;br /&gt;
'''Flash Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. A lightweight object that helps us store the information of the state the application is in.&amp;lt;br&amp;gt;&lt;br /&gt;
2. Since flash is similar to hash, it helps us abuse the advantages of hash. &amp;lt;br&amp;gt;&lt;br /&gt;
3. Any key can be passed into the flash object and the user is responsible for extracting the information from the corresponding object &amp;lt;br&amp;gt;&lt;br /&gt;
4. It is less tedious to manage as its lifetime persists only until the next request.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. As the information stored in the flash object persists only until the next request, it is not useful for providing security related capabilities to &lt;br /&gt;
   the application.&amp;lt;br&amp;gt;&lt;br /&gt;
2. It has limited capabilities and used for displaying simple error messages, notices or warnings in the application.&amp;lt;br&amp;gt;&lt;br /&gt;
3. It cannot store dynamic information.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion/Summary =&lt;br /&gt;
&lt;br /&gt;
HTTP is a stateless protocol and the web applications require saving of the application state frequently. Based on the application state, certain actions are taken. This is possible in RUBY using redirection flash object. The redirection flash object persists for a short duration and helps us store simple information about the application. Another flash like object that provides us very rich capabilities in terms of information storge, authentication and security is the session object. We have seen the differences between the two. It is the programmers responsibility to appropriately use the flash or the session object depending on what needs to be achieved.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions_controller&lt;br /&gt;
http://www.tutorialspoint.com/ruby-on-rails/rails-session-cookies.htm&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67221</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w67 ks</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w67_ks&amp;diff=67221"/>
		<updated>2012-10-04T02:41:57Z</updated>

		<summary type="html">&lt;p&gt;Knagar: /* Session in Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;                                                            &lt;br /&gt;
= Overview/Introduction =&lt;br /&gt;
&amp;lt;p&amp;gt; Redirection in ruby refers to the where a user is redirected from one page to another. HTTP is stateless, hence session/flash makes it stateful.As the http requests are stateless, hence this leads to losing all the state that we had before. Thus Rails provides a hash called Flash such that it persists until the end of the next request received.&lt;br /&gt;
Also there is a session hash, which unlike flash persists forever. &amp;lt;ref&amp;gt;http://www.youtube.com/watch?v=0m8lmRwS7E0&amp;lt;/ref&amp;gt;.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;p&amp;gt;For information on how to format the text of your article, create tables, and use section headings and references, see this [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/WIKI_Features article].&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Flash in Ruby =&lt;br /&gt;
&amp;lt;p&amp;gt;Flash in ruby helps to remember the state until the end of the next request. It is basically used to store error messages as warnings and information as notice in the hash. This is used in views to print the error messages or notice. Instead of notice or warnings, we can define user defined hash and print its value in the view as we did for the notice and warnings. Basically it helps in flashing messages on the views. It stores values in the form of hash table. It is particularly useful to show messages after a redirect.Whenever you want to display any kind of status message or error message &amp;quot;Your email id is updated&amp;quot; or &amp;quot;Invalid Password&amp;quot; etc.&lt;br /&gt;
Rails loads it when you set it in your controller code and it is displayed in your view (if you have it set to display in the view). Rails discards the value when it is rendered on the client. The Flash values set in either notice/error or any user defined message in the controller can be accessed in the views to display the result of the action taken place in the controller.&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Session in Ruby =&lt;br /&gt;
Most applications need to keep track of certain state of a particular user. Examples include shopping cart for online shopping account or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.&lt;br /&gt;
&lt;br /&gt;
A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client’s browser includes the session id. And the other way round, the browser will send it to the server on every request from the client. &lt;br /&gt;
&lt;br /&gt;
In Ruby session persists forever and is stored in the browser cookies by default. The session data can thus be deleted by clearing content of the cookies. Session is useful when we have to remember the state for  a long time. Examples include Authentication where the user enters its login id and password that needs to be available for the whole session that the user is logged in. There are some alternative storage modes for session such as Storage table or No SQL data structure.&amp;lt;ref name=&amp;quot;ref5&amp;quot;&amp;gt; http://refactoring.com/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= How it works =&lt;br /&gt;
&lt;br /&gt;
== Session  ==&lt;br /&gt;
Session stores small amount of data that persists between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms such as cookies, tables, cache, memcache etc.&lt;br /&gt;
The session stores session id in cookies as it is insecure when embedded in the url.This unique id is used to look up the session data on its storage locations such as cookies, database tables, no sql data structure, cache etc.The data storage in cookies by default makes the session lightweight and easy to access and it does not requires calls to the storage locations for accessing the session data. The cookies can store atmost 4 kb data and hence gives cookie overflow exception if the data in the session exceeds the 4 kb limit.The cookie data is not encrypted but it cannot be edited by being visible in the url. &amp;lt;ref name=&amp;quot;ref1&amp;quot;&amp;gt; http://guides.rubyonrails.org/security.html#sessions/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
Session values are stored in a key,value pair. In Ruby we store it like a hash.&lt;br /&gt;
&lt;br /&gt;
1. To add a session attribute we say &lt;br /&gt;
   session[:username]=params[:username]. &lt;br /&gt;
   Here we assign the username received from the user to the session variable.&lt;br /&gt;
2. To delete a session attribute value, just assign the key to nil.&lt;br /&gt;
   eg: session[:username]=nil. &lt;br /&gt;
   Here we are deleting the session attribute username.&lt;br /&gt;
3. The session can also be reset &lt;br /&gt;
   reset_session&lt;br /&gt;
   This will reset the complete session hash&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Flash is used by the controller to pass messages to the view. The controller can pass messages about the success or failure of the desired action. In Ruby,w e can also pass the flash message as part of the redirection again informing the view about the state of the action performed when redirecting. The user can also pass user defined messages and also pass messages for debugging purposes. The flash message displayed on the form/view is now taken care by the next request. The layout that receives the flash has to decide the action to be performed on the basis of the message received from the flash.&amp;lt;ref name=&amp;quot;ref4&amp;quot;&amp;gt;http://guides.rubyonrails.org/action_controller_overview.html#the-flash &amp;lt;/ref&amp;gt;&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. To set a  flash value as a notice &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
   flash[:notice]= &amp;quot;User logged in successfully&amp;quot; &lt;br /&gt;
   The flash message sets the notice value. This flashes the notice on the form when the user successfully logs into the system.  &lt;br /&gt;
&lt;br /&gt;
2. To set a flash value as a warning &amp;lt;ref name=&amp;quot;ref3&amp;quot;&amp;gt;http://pupeno.com/2009/11/19/ensuring-the-displaying-of-flash-messages-in-ruby-on-rails/ &amp;lt;/ref&amp;gt;&lt;br /&gt;
    flash[:error]= &amp;quot;Please provide the username and password&amp;quot; &lt;br /&gt;
    The flash message sets the error value. This automatically flashes the notice saying that the user did not provide the username and password.  &lt;br /&gt;
&lt;br /&gt;
3. To set flash message as part of redirection&lt;br /&gt;
   redirect_to( posts_show,  :notice =&amp;gt; &amp;quot;Post successfully created&amp;quot; )&lt;br /&gt;
   The above statement redirects the method call to the appropriate url and displays a notice there automatically saying the post was successfully &lt;br /&gt;
   created.&lt;br /&gt;
&lt;br /&gt;
4. The value of flash to be saved for the subsequent requests&lt;br /&gt;
   flash.keep&lt;br /&gt;
   The above statement keeps all values of flash, that resulted from the redirection, to be used in the subsequent requests.&lt;br /&gt;
&lt;br /&gt;
5.  The value of flash to be saved in the current request &lt;br /&gt;
    flash.now&lt;br /&gt;
    The above statement keeps the values of flash, that resulted from the redirection, to be used for the current request.&lt;br /&gt;
&lt;br /&gt;
= Example - Session/Flash =&lt;br /&gt;
&lt;br /&gt;
:Class ExamplesController &amp;lt; ApplicationController&amp;lt;br&amp;gt;&lt;br /&gt;
::def index&lt;br /&gt;
::'''session[:example_name]=params[:example][:name]'''&lt;br /&gt;
::...&lt;br /&gt;
::end&lt;br /&gt;
::def update&lt;br /&gt;
:::@example = Example.find(params[:id])&lt;br /&gt;
:::respond_to do |format|&lt;br /&gt;
::::if @example.update_attributes(params[:type])&lt;br /&gt;
:::::format.html {redirect_to(@example, '''flash[:notice] =&amp;gt; 'Example was successfully updated.'''')}&lt;br /&gt;
::::else&lt;br /&gt;
:::::format.html { render :action =&amp;gt; &amp;quot;edit&amp;quot; }&lt;br /&gt;
::::end&lt;br /&gt;
:::end&lt;br /&gt;
::end&lt;br /&gt;
::def &lt;br /&gt;
::....&lt;br /&gt;
::end&lt;br /&gt;
:end&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''In the show(@example) view, we can make use of session and flash as- '''&lt;br /&gt;
&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;notice&amp;quot;&amp;gt;&amp;lt;%=notice%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
'''&amp;lt;p id= &amp;quot;example name&amp;quot;&amp;gt;&amp;lt;%=session[:example_name]%&amp;gt;&amp;lt;/p&amp;gt;'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above code, the ExampleController class has a index method that sets the session for the user and &lt;br /&gt;
update method that sets the flash variable ,we set the session variable with the name of the example obtained from&lt;br /&gt;
the user stored in the params hash, we can access it in any view in that session.In the update method, flash is used to set&lt;br /&gt;
the notice to a desired value. Then it is used in the view  to display the message.&lt;br /&gt;
&lt;br /&gt;
= Advantages/Disadvantages =&lt;br /&gt;
&lt;br /&gt;
== Session ==&lt;br /&gt;
&lt;br /&gt;
'''Session Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 1.A session object helps us store useful information about the application like the session_id, currently logged in user details. &amp;lt;br&amp;gt;&lt;br /&gt;
 2.It is similar to hash and helps us take advantages of the hash functionalities in Ruby. &amp;lt;br&amp;gt;&lt;br /&gt;
 3.Since, it persists forever, the session variables can be used to perform authentication,server side validation and take care of the security aspects &lt;br /&gt;
   of the application. &amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Session Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. The session object is a heavy weight object as it is used to store a lot of application related information.&amp;lt;br&amp;gt;&lt;br /&gt;
2. we have to be careful while dealing with session variables as it is subject to malicious attacks and sensitive information can be divulged if not &lt;br /&gt;
   taken care of while programming. &amp;lt;br&amp;gt;&lt;br /&gt;
3. As the session variables persists forever, it is the programmers responsibility to reset the information of the application when the application goes &lt;br /&gt;
   out of the current scope logically. &amp;lt;br&amp;gt;&lt;br /&gt;
4. Too many session variable manipulation and storage can make the code inefficient and can cause unexpected behaviour if not programmed carefully.&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Flash ==&lt;br /&gt;
&lt;br /&gt;
'''Flash Advantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. A lightweight object that helps us store the information of the state the application is in.&amp;lt;br&amp;gt;&lt;br /&gt;
2. Since flash is similar to hash, it helps us abuse the advantages of hash. &amp;lt;br&amp;gt;&lt;br /&gt;
3. Any key can be passed into the flash object and the user is responsible for extracting the information from the corresponding object &amp;lt;br&amp;gt;&lt;br /&gt;
4. It is less tedious to manage as its lifetime persists only until the next request.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Disadvantages:'''&lt;br /&gt;
&amp;lt;p&amp;gt;&lt;br /&gt;
1. As the information stored in the flash object persists only until the next request, it is not useful for providing security related capabilities to &lt;br /&gt;
   the application.&amp;lt;br&amp;gt;&lt;br /&gt;
2. It has limited capabilities and used for displaying simple error messages, notices or warnings in the application.&amp;lt;br&amp;gt;&lt;br /&gt;
3. It cannot store dynamic information.&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion/Summary =&lt;br /&gt;
&lt;br /&gt;
HTTP is a stateless protocol and the web applications require saving of the application state frequently. Based on the application state, certain actions are taken. This is possible in RUBY using redirection flash object. The redirection flash object persists for a short duration and helps us store simple information about the application. Another flash like object that provides us very rich capabilities in terms of information storge, authentication and security is the session object. We have seen the differences between the two. It is the programmers responsibility to appropriately use the flash or the session object depending on what needs to be achieved.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec:sessions_controller&lt;br /&gt;
http://www.tutorialspoint.com/ruby-on-rails/rails-session-cookies.htm&lt;/div&gt;</summary>
		<author><name>Knagar</name></author>
	</entry>
</feed>