<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Java Blog &#187; Design Patterns</title>
	<atom:link href="http://javapapers.com/category/design-patterns/feed/" rel="self" type="application/rss+xml" />
	<link>http://javapapers.com</link>
	<description>Blog on core java, servlets, jsp and design patterns.</description>
	<lastBuildDate>Sun, 03 Jun 2012 11:34:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Composite Design Pattern</title>
		<link>http://javapapers.com/design-patterns/composite-design-pattern/</link>
		<comments>http://javapapers.com/design-patterns/composite-design-pattern/#comments</comments>
		<pubDate>Sun, 13 May 2012 07:54:47 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=797</guid>
		<description><![CDATA[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&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<p>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&#8217;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.</p>
<p>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, &#8230; Engine is made up of electrical components, valves, &#8230; Electrical components is made up of chips, transistor, &#8230; Like this a component is part of a whole system. This hierarchy can be represented as a tree structure using composite design pattern.<img class="alignright size-full wp-image-798" title="legos" src="http://javapapers.com/wp-content/uploads/2012/05/legos.jpg" alt="" width="250" height="173" /></p>
<p>&#8220;Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.&#8221; is the intent by GoF.</p>
<h2>Real World Example</h2>
<p>In this article, let us take a real world example of part-whole hierarchy and use composite design pattern using java. As a kid, I have spent huge amount of time with lego building blocks. Last week I bought my son an assorted kit lego and we spent the whole weekend together building structures.</p>
<p>Let us consider the game of building blocks to practice composite pattern. Assume that our kit has only three unique pieces ( 1, 2 and 4 blocks) and let us call these as primitive blocks as they will be the end nodes in the tree structure. Objective is to build a house and it will be a step by step process. First using primitive blocks, we should construct multiple windows, doors, walls, floor and let us call these structures.  Then use all these structure to create a house.</p>
<p><img class="alignright size-full wp-image-799" title="house" src="http://javapapers.com/wp-content/uploads/2012/05/house.jpg" alt="" width="300" height="203" /></p>
<p>Primitive blocks combined together gives a structure. Multiple structures assembled together gives a house.</p>
<h2>Important Points</h2>
<ul>
<li>Importance of composite pattern is, the group of objects should be treated similarly as a single object.</li>
<li>Manipulating a single object should be as similar to manipulating a group of objects. In sync with our example, we join primitive blocks to create structures and similarly join structures to create house.</li>
<li>Recursive formation and tree structure for composite should be noted.</li>
<li>Clients access the whole hierarchy through the components and they are not aware about if they are dealing with leaf or composites.</li>
</ul>
<h2>Tree for Composite</h2>
<p>When we get a recursive structure the obvious choice for implementation is a tree. In composite design pattern, the part-whole hierarchy can be represented as a tree. Leaves (end nodes) of a tree being the primitive elements and the tree being the composite structure.</p>
<p><img class="alignright size-full wp-image-802" title="block_tree" src="http://javapapers.com/wp-content/uploads/2012/05/block_tree.png" alt="" width="350" height="168" /></p>
<h2>Uml Design for Composite Pattern</h2>
<p>Component: (structure)</p>
<ol>
<li> Component is at the top of hierarchy. It is an abstraction for the composite.</li>
<li>It declares the interface for objects in composition.</li>
<li>(optional) defines an interface for accessing a component&#8217;s parent in the recursive structure, and implements it if that&#8217;s appropriate.</li>
</ol>
<p>Leaf: (primitive blocks)</p>
<ol>
<li> The end nodes of the tree and will not have any child.</li>
<li>Defines the behaviour for single objects in the composition</li>
</ol>
<p>Composite: (group)</p>
<ol>
<li> Consists of child components and defines behaviour for them</li>
<li>Implements the child related operations.</li>
</ol>
<p><img class="alignright size-full wp-image-806" title="composite" src="http://javapapers.com/wp-content/uploads/2012/05/composite.jpg" alt="" width="341" height="295" /></p>
<h2>Composite Pattern Implementation</h2>
<pre class="brush: java;">
package com.javapapers.designpattern.composite;

public class Block implements Group {

    public void assemble() {
        System.out.println(&quot;Block&quot;);
    }
}
</pre>
<pre class="brush: java;">
package com.javapapers.designpattern.composite;

public interface Group {
    public void assemble();
}
</pre>
<pre class="brush: java;">
package com.javapapers.designpattern.composite;

import java.util.ArrayList;
import java.util.List;

public class Structure implements Group {
	// Collection of child groups.
	private List&lt;Group&gt; groups = new ArrayList&lt;Group&gt;();

	public void assemble() {
		for (Group group : groups) {
			group.assemble();
		}
	}

	// Adds the group to the structure.
	public void add(Group group) {
		groups.add(group);
	}

	// Removes the group from the structure.
	public void remove(Group group) {
		groups.remove(group);
	}
}
</pre>
<pre class="brush: java;">
package com.javapapers.designpattern.composite;

public class ImplementComposite {
	 public static void main(String[] args) {
	        //Initialize three blocks
	        Block block1 = new Block();
	        Block block2 = new Block();
	        Block block3 = new Block();

	        //Initialize three structure
	        Structure structure = new Structure();
	        Structure structure1 = new Structure();
	        Structure structure2 = new Structure();

	        //Composes the groups
	        structure1.add(block1);
	        structure1.add(block2);

	        structure2.add(block3);

	        structure.add(structure1);
	        structure.add(structure2);

	        structure.assemble();
	    }
}
</pre>
<h2>Usage of Composite Design Pattern in Sun/Oracle JDK</h2>
<ul>
<li>java.awt.Container#add(Component) &#8211; in awt, we have containers and components &#8211; a classic implementation</li>
<li>javax.faces.component.UIComponent#getChildren()</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/design-patterns/composite-design-pattern/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Proxy Design Pattern</title>
		<link>http://javapapers.com/design-patterns/proxy-design-pattern/</link>
		<comments>http://javapapers.com/design-patterns/proxy-design-pattern/#comments</comments>
		<pubDate>Sun, 01 Apr 2012 17:19:33 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=771</guid>
		<description><![CDATA[&#8220;Provide a surrogate or placeholder for another object to control access to it&#8221; is the intent provided by GoF. Proxy means &#8216;in place of&#8217;. In attendance roll call, we give proxy for our friends in college right? &#8216;Representing&#8217; or &#8216;in place of&#8217; or &#8216;on behalf of&#8217; are literal meanings of proxy and that directly explains [...]]]></description>
			<content:encoded><![CDATA[<p>&#8220;Provide a surrogate or placeholder for another object to control access to it&#8221; is the intent provided by GoF.</p>
<p>Proxy means &#8216;in place of&#8217;. In attendance roll call, we give proxy for our friends in college right? &#8216;Representing&#8217; or &#8216;in place of&#8217; or &#8216;on behalf of&#8217; are literal meanings of proxy and that directly explains proxy design pattern. It is one of the simplest and straight forward <a title="Introduction To Design Patterns" href="http://javapapers.com/design-patterns/introduction-to-design-patterns/">design pattern</a>.</p>
<p>Proxy design pattern gets second rank in popularity in interviews. Guess who gets the first rank? none other than <a title="Singleton Design Pattern" href="http://javapapers.com/design-patterns/singleton-pattern/">singleton design pattern</a>.</p>
<p><img class="alignright size-full wp-image-772" title="Proxy Design Pattern" src="http://javapapers.com/wp-content/uploads/2012/04/Proxy.png" alt="" width="312" height="391" /></p>
<h2>Possible Usage Scenarios</h2>
<ul>
<li>Remote Proxy &#8211; Represents an object locally which belongs to a different address space. 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.</li>
<li>Virtual Proxy &#8211; 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.</li>
<li>Protection Proxy &#8211; Are you working on a MNC? If so, 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.</li>
<li>Smart Reference &#8211; Just we keep a link/reference to the real object a kind of pointer.</li>
</ul>
<h2>Proxy Design Pattern Example</h2>
<p>Remote Proxy:</p>
<p><img class="alignright size-full wp-image-773" title="Remote Proxy" src="http://javapapers.com/wp-content/uploads/2012/04/Remote-Proxy.png" alt="" width="350" height="170" /><br />
Sometime back I wrote an article on A helloworld for Soap Web Service. A part of it contains implementation of proxy design pattern. The client has the stub files generated which acts as a proxy for the classes in server side.</p>
<p><img class="alignright size-full wp-image-774" title="Remote Proxy Example" src="http://javapapers.com/wp-content/uploads/2012/04/Remote-Proxy-Example.png" alt="" width="310" height="336" /></p>
<h2>Java&#8217;s Support for Proxy Design Pattern</h2>
<p>From <a title="Java Versions, Features and History" href="http://javapapers.com/core-java/java-features-and-history/">JDK 1.3</a> 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&#8217;s api for proxy design pattern.</p>
<pre class="brush: java;">
package com.javapapers.designpattern.proxy;

public interface Animal {

	public void getSound();

}
</pre>
<pre class="brush: java;">
package com.javapapers.designpattern.proxy;

public class Lion implements Animal {

	public void getSound() {
		System.out.println(&quot;Roar&quot;);
	}

}
</pre>
<pre class="brush: java;">
package com.javapapers.designpattern.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class AnimalInvocationHandler implements InvocationHandler {
	public AnimalInvocationHandler(Object realSubject) {
		this.realSubject = realSubject;
	}

	public Object invoke(Object proxy, Method m, Object[] args) {
		Object result = null;
		try {
			result = m.invoke(realSubject, args);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	private Object realSubject = null;
}
</pre>
<pre class="brush: java;">
package com.javapapers.designpattern.proxy;

import java.lang.reflect.Proxy;

public class ProxyExample {

	public static void main(String[] args) {
		Animal realSubject = new Lion();
		Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()
				.getClassLoader(), realSubject.getClass().getInterfaces(),
				new AnimalInvocationHandler(realSubject));
		proxy.getSound();
	}
}
</pre>
<h2><a href="http://javapapers.com/wp-content/uploads/2012/04/proxy-src.zip">Download Proxy Example Source</a></h2>
<h2>Important Points</h2>
<ul>
<li>A proxy may hide information about the real object to the client.</li>
<li>A proxy may perform optimization like on demand loading.</li>
<li>A proxy may do additional house-keeping job like audit tasks.</li>
<li>Proxy design pattern is also known as surrogate design pattern.</li>
</ul>
<h2>Proxy Design Pattern Usage in Java API</h2>
<ul>
<li>java.rmi.* &#8211; RMI package is based on proxy design pattern</li>
</ul>
<h2>Adapter vs Proxy Design Pattern</h2>
<p><a title="Adapter Design Pattern" href="http://javapapers.com/design-patterns/adapter-pattern/">Adapter design pattern</a> provides a different interface from the real object and enables the client to use it to interact with the real object. But, proxy design pattern provides the same interface as in the real object.</p>
<h2>Decorator vs Proxy Design Patter</h2>
<p><a title="Decorator Design Pattern" href="http://javapapers.com/design-patterns/decorator-pattern/">Decorator design pattern</a> adds behaviour at runtime to the real object. But, Proxy does not change the behaviour instead it controls the behaviour.</p>
]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/design-patterns/proxy-design-pattern/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Bridge Design Pattern</title>
		<link>http://javapapers.com/design-patterns/bridge-design-pattern/</link>
		<comments>http://javapapers.com/design-patterns/bridge-design-pattern/#comments</comments>
		<pubDate>Sun, 05 Feb 2012 15:25:54 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=703</guid>
		<description><![CDATA[&#8220;Decouple an abstraction from its implementation so that the two can vary independently&#8221; is the intent for bridge design pattern as stated by GoF. Bridge design pattern is a modified version of the notion of &#8220;prefer composition over inheritance&#8221;. Problem and Need for Bridge Design Pattern When there are inheritance hierarchies creating concrete implementation, you loose [...]]]></description>
			<content:encoded><![CDATA[<p>&#8220;Decouple an abstraction from its implementation so that the two can vary independently&#8221; is the intent for bridge design pattern as stated by GoF.</p>
<p>Bridge design pattern is a modified version of the notion of &#8220;prefer composition over inheritance&#8221;.</p>
<h2>Problem and Need for Bridge Design Pattern</h2>
<p>When there are inheritance hierarchies creating concrete implementation, you loose flexibility because of interdependence. Oops! these kind of sentencies shows that the author(I) didn&#8217;t understand and tries to escape! Okay, I will decrypt this sentence in the coming paragraphs.</p>
<p>Decouple implentation from interface and hiding implementation details from client is the essense of bridge design pattern.</p>
<h2>Elements of Bridge Design Pattern</h2>
<ul>
<li>Abstraction &#8211; core of the bridge design pattern and defines the crux. Contains a reference to the implementer.</li>
<li>Refined Abstraction &#8211; Extends the abstraction takes the finer detail one level below. Hides the finer elements from implemetors.</li>
<li>Implementer - This interface is the higer level than abstraction. Just defines the basic operations.</li>
<li>Concrete Implementation &#8211; Implements the above implementer by providing concrete implementation.</li>
</ul>
<h2>Example for core elements of Bridge Design Pattern</h2>
<blockquote><p>Vehicle -&gt; Abstraction<br />
manufacture()</p>
<p>Car -&gt; Refined Abstraction 1<br />
manufacture()</p>
<p>Bike -&gt; Refined Abstraction 2<br />
manufacture()</p>
<p>Workshop -&gt; Implementor<br />
work()</p>
<p>Produce -&gt; Concrete Implementation 1<br />
work()</p>
<p>Assemble -&gt; Concrete Implementation 2<br />
work()</p></blockquote>
<h2>Generic UML Diagram for Bridge Design Pattern</h2>
<p><img class="alignright size-full wp-image-704" title="Bridge Pattern" src="http://javapapers.com/wp-content/uploads/2012/02/Bridge-Pattern.jpg" alt="" width="332" height="222" /></p>
<h2>Before Bridge Design Pattern</h2>
<p><img class="alignright size-full wp-image-705" title="Before Bridge" src="http://javapapers.com/wp-content/uploads/2012/02/Before-Bridge.jpg" alt="" width="324" height="256" /></p>
<h2>After Bridge Design Pattern</h2>
<p><img class="alignright size-full wp-image-706" title="After Bridge" src="http://javapapers.com/wp-content/uploads/2012/02/After-Bridge.jpg" alt="" width="321" height="174" /></p>
<h2>Sample Java Code for Bridge Design Pattern</h2>
<pre class="brush: java;">

package com.javapapers.designpattern;

/**
 * abstraction in bridge pattern
 * */
abstract class Vehicle {
	protected Workshop workShop1;
	protected Workshop workShop2;

	protected Vehicle(Workshop workShop1, Workshop workShop2) {
		this.workShop1 = workShop1;
		this.workShop2 = workShop2;
	}

	abstract public void manufacture();
}

package com.javapapers.designpattern;

/**
 * Refine abstraction 1 in bridge pattern
 */
public class Car extends Vehicle {

	public Car(Workshop workShop1, Workshop workShop2) {
		super(workShop1, workShop2);
	}

	@Override
	public void manufacture() {
		System.out.print(&quot;Car &quot;);
		workShop1.work();
		workShop2.work();

	}

}

package com.javapapers.designpattern;

/**
 * Refine abstraction 2 in bridge pattern
 */
public class Bike extends Vehicle {

	public Bike(Workshop workShop1, Workshop workShop2) {
		super(workShop1, workShop2);
	}

	@Override
	public void manufacture() {
		System.out.print(&quot;Bike &quot;);
		workShop1.work();
		workShop2.work();
	}

}

package com.javapapers.designpattern;

/**
 * Implementor for bridge pattern
 * */
public interface Workshop {
	abstract public void work();
}

package com.javapapers.designpattern;

/**
 * Concrete implementation 1 for bridge pattern
 * */
public class Produce implements Workshop {

	@Override
	public void work() {
		System.out.print(&quot;Produced&quot;);
	}

}

package com.javapapers.designpattern;

/**
 * Concrete implementation 2 for bridge pattern
 * */
public class Assemble implements Workshop {

	@Override
	public void work() {
		System.out.println(&quot; Assembled.&quot;);
	}

}

package com.javapapers.designpattern;

/*
 * Demonstration of bridge design pattern
 */
public class BridgePattern {

	public static void main(String[] args) {

		Vehicle vehicle1 = new Car(new Produce(), new Assemble());
		vehicle1.manufacture();
		Vehicle vehicle2 = new Bike(new Produce(), new Assemble());
		vehicle2.manufacture();

	}
}

Output:
Car Produced Assembled.
Bike Produced Assembled.
</pre>
<h2>Summary of Bridge Design Pattern</h2>
<ul>
<li>Creates two different hierarchies. One for abstraction and another for implementation.</li>
<li>Avoids permanent binding by removing the dependency between abstraction and implementation.</li>
<li>We create a bridge that coordinates between abstraction and implementation.</li>
<li>Abstraction and implementation can be extended separately.</li>
<li>Should be used when we have need to switch implementation at runtime.</li>
<li>Client should not be impacted if there is modification in implementation of abstraction.</li>
<li>Best used when you have multiple implementations.</li>
</ul>
<h2>Bridge Vs Adapter Design Pattern</h2>
<p>The <a title="Adapter Design Pattern" href="http://javapapers.com/design-patterns/adapter-pattern/">adapter design pattern</a> helps it two incompatible classes to work together. But, bridge design pattern decouples the abstraction and implementation by creating two different hierarchies.</p>
]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/design-patterns/bridge-design-pattern/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Facade Design Pattern</title>
		<link>http://javapapers.com/design-patterns/facade-design-pattern/</link>
		<comments>http://javapapers.com/design-patterns/facade-design-pattern/#comments</comments>
		<pubDate>Sun, 29 Jan 2012 12:31:06 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=688</guid>
		<description><![CDATA[GoF definition for facade design pattern is, &#8220;Provide a unified interface to a set of interfaces in a subsystem. Facade Pattern defines a higher-level interface that makes the subsystem easier to use.&#8221; How do we infer the above definition? Think of a component that solves a complex business problem. That component may expose lot of [...]]]></description>
			<content:encoded><![CDATA[<p>GoF definition for facade design pattern is, &#8220;Provide a unified interface to a set of interfaces in a subsystem. Facade Pattern defines a higher-level interface that makes the subsystem easier to use.&#8221;</p>
<p>How do we infer the above definition? Think of a component that solves a complex business problem. That component may expose lot of interfaces to interact with it. To complete a process flow we may have to interact with multiple interfaces.</p>
<p>To simplify that interaction process, we introduce facade layer. Facade exposes a simplified interface (in this case a single interface to perform that multi-step process) and internally it interacts with those components and gets the job done for you. It can be taken as one level of abstraction over an existing layer.</p>
<p><img class="alignright size-full wp-image-690" title="Before Facade Design Pattern" src="http://javapapers.com/wp-content/uploads/2012/01/facade_complex.jpg" alt="" width="300" height="386" /></p>
<p>Facade design pattern is one among the other <a title="Introduction To Design Patterns" href="http://javapapers.com/design-patterns/introduction-to-design-patterns/">design patterns</a> that promote loose coupling. It emphasizes one more important aspect of design which is abstraction. By hiding the complexity behind it and exposing a simple interface it achieves abstraction.</p>
<p><img class="alignright size-full wp-image-691" title="After Facade Design Pattern" src="http://javapapers.com/wp-content/uploads/2012/01/facade_simple.jpg" alt="" width="300" height="415" /></p>
<h2>Real World Examples for Facade Pattern</h2>
<p>I wish to give you couple of real world examples. Lets take a car, starting a car involves multiple steps. Imagine how it would be if you had to adjust n number of valves and controllers. The facade you have got is just a key hole. On turn of a key it send instruction to multiple subsystems and executes a sequence of operation and completes the objective. All you know is a key turn which acts as a facade and simplifies your job.</p>
<p>Similarly consider microwave oven, it consists of components like trasnformer, capacitor, magnetron, waveguide and some more. To perform an operation these different components needs to be activated in a sequence. Every components has different outputs and inputs. Imagine you will have separate external controller for all these components using which you will heat the food. It will be complicated and cumbersome.</p>
<p>In this scenario, oven provides you preprogrammed switches which can be considered as a facade. On click on of a single switch the job gets done. That single menu switch works as an abstraction layer between you and the internal components.</p>
<p>These are realworld examples for facade design pattern. In software scenario, you can have interfaces which acts as a facade. Methods in these interfaces contains the interaction sequence, formatting and converting data for input for components. As such it will not hold the business logic.</p>
<h2>UML Diagram for Facade Design Pattern</h2>
<p><img class="alignright size-full wp-image-689" title="FacadeUml" src="http://javapapers.com/wp-content/uploads/2012/01/FacadeUml.jpg" alt="" width="350" height="312" /></p>
<h2>Common Mistakes while Implementing Facade Design Pattern</h2>
<p>In my experience the common mistakes I have seen is,</p>
<ul>
<li>just for the sake of introducing a facade layer developers tend to create additional classes. Layered architecture is good but assess the need for every layer. Just naming a class as ABCDFacade.java doesn&#8217;r really make it a facade.</li>
<li>Creating a java class and &#8216;forcing&#8217; the UI to interact with other layers through it and calling it a facade layer is one more popular mistake. Facade layer should not be forced and its always optional. If the client wishes to interact with components directly it should be allowed to bypass the facade layer.</li>
<li>Methods in facade layer has only one or two lines which calls the other components. If facade is going to be so simple it invalidates its purpose and clients can directly do that by themselves.</li>
<li>A controller is not a facade.</li>
<li>Facade is &#8216;not&#8217; a layer that imposes security and hides important data and implementation.</li>
<li>Don&#8217;t create a facade layer in advance. If you feel that in future the subsystem is going to evolve and become complicated to defend that do not create a stub class and name it a facade. After the subsystem has become complex you can implement the facade design pattern.</li>
<li>Subsystems are not aware of facade and there should be no reference for facade in subsystems.</li>
</ul>
<h2>Summary of Facade Design Pattern</h2>
<ul>
<li>Facade provides a single interface.</li>
<li>Programmers comfort is a main purpose of facade.</li>
<li>Simplicity is the aim of facade pattern.</li>
<li>Facade design pattern is used for promoting subsystem independence and portability.</li>
<li>Subsystem may be dependent with one another. In such case, facade can act as a coordinator and decouple the dependencies between the subsystems.</li>
<li>Translating data to suit the interface of a subsystem is done by the facade.</li>
</ul>
<h2>Facade Vs Mediator Design Pattern</h2>
<p>Mediator design pattern may look very similar to facade design pattern in terms of abstraction. Mediator abstracts the functionality of the subsystems in this way it is similar to the facade pattern. In the implementation of mediator pattern, subsystem or peers components are aware of the mediator and that interact with it. In the case of facade pattern, subsystems are not aware of the existence of facade. Only facade talks to the subsystems.</p>
<h2>Facade Design Pattern in Java API</h2>
<p><a title="ExternalContext API" href="http://docs.oracle.com/javaee/6/api/javax/faces/context/ExternalContext.html">ExternalContext</a> behaves as a facade for performing cookie, session scope and similar operations. Underlying classes it uses are HttpSession, ServletContext, javax.servlet.http.HttpServletRequest and javax.servlet.http.HttpServletResponse.</p>
]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/design-patterns/facade-design-pattern/feed/</wfw:commentRss>
		<slash:comments>32</slash:comments>
		</item>
		<item>
		<title>Decorator Design Pattern</title>
		<link>http://javapapers.com/design-patterns/decorator-pattern/</link>
		<comments>http://javapapers.com/design-patterns/decorator-pattern/#comments</comments>
		<pubDate>Tue, 17 May 2011 00:01:12 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=552</guid>
		<description><![CDATA[To extend or modify the behaviour of &#8216;an instance&#8217; at runtime decorator design pattern is used. Inheritance is used to extend the abilities of &#8216;a class&#8217;. Unlike inheritance, you can choose any single object of a class and modify its behaviour leaving the other instances unmodified. In implementing the decorator pattern you construct a wrapper [...]]]></description>
			<content:encoded><![CDATA[<p>To extend or modify the behaviour of &#8216;an instance&#8217; at runtime decorator <a title="Introduction To Design Patterns" href="http://javapapers.com/design-patterns/introduction-to-design-patterns/">design pattern</a> is used. Inheritance is used to extend the abilities of &#8216;a class&#8217;. Unlike inheritance, you can choose any single object of a class and <a title="Overloading vs Overriding" href="http://javapapers.com/core-java/overloading-and-overriding/">modify its behaviour</a> leaving the other instances unmodified.</p>
<p>In implementing the decorator pattern you construct a wrapper around an object by extending its behavior. The wrapper will do its job before or after and delegate the call to the wrapped instance.</p>
<p><a href="http://javapapers.com/wp-content/uploads/2011/05/decorated-icecream.jpg"><img class="alignright size-medium wp-image-557" title="decorated icecream" src="http://javapapers.com/wp-content/uploads/2011/05/decorated-icecream-213x300.jpg" alt="" width="213" height="300" /></a></p>
<h2>Design of decorator pattern</h2>
<p>You start with an <a title="Java interface" href="http://javapapers.com/core-java/abstract-and-interface-core-java-2/java-interface/">interface</a> which creates a blue print for the class which will have decorators. Then implement that interface with basic functionalities. Till now we have got an interface and an implementation concrete class. Create an <a title="Difference Between Interface and Abstract Class" href="http://javapapers.com/core-java/abstract-and-interface-core-java-2/difference-between-a-java-interface-and-a-java-abstract-class/">abstract class</a> that contains (<a title="Association, Aggregation, Composition, Abstraction, Generalization, Realization, Dependency" href="http://javapapers.com/oops/association-aggregation-composition-abstraction-generalization-realization-dependency/">aggregation relationship</a>) an attribute type of the interface. The constructor of this class assigns the interface type instance to that attribute. This class is the decorator base class. Now you can extend this class and create as many concrete decorator classes. The concrete decorator class will add its own methods. After / before executing its own method the concrete decorator will call the base instance&#8217;s method. Key to this decorator design pattern is the binding of method and the base instance happens at runtime based on the object <a title="Java Pass By Value and Pass By Reference." href="http://javapapers.com/core-java/java-pass-by-value-and-pass-by-reference/">passed as parameter</a> to the constructor. Thus dynamically customizing the behavior of that specific instance alone.</p>
<h2>Decorator Design Pattern &#8211; UML Diagram</h2>
<p><img class="alignright size-full wp-image-553" title="Decorator Design Pattern - UML Diagram" src="http://javapapers.com/wp-content/uploads/2011/05/Decorator-Pattern.jpg" alt="" width="359" height="459" /></p>
<h2>Implementation of decorator pattern</h2>
<p>Following given example is an implementation of decorator design pattern. Icecream is a classic example for decorator design pattern. You create a basic icecream and then add toppings to it as you prefer. The added toppings change the taste of the basic icecream. You can add as many topping as you want. This sample scenario is implemented below.</p>
<pre class="brush: java;">
package com.javapapers.sample.designpattern;

public interface Icecream {
  public String makeIcecream();
}
</pre>
<p>The above is an interface depicting an icecream. I have kept things as simple as possible so that the focus will be on understanding the design pattern. Following class is a concrete implementation of this interface. This is the base class on which the decorators will be added.</p>
<pre class="brush: java;">
package com.javapapers.sample.designpattern;

public class SimpleIcecream implements Icecream {

  @Override
  public String makeIcecream() {
    return &quot;Base Icecream&quot;;
  }

}
</pre>
<p>Following class is the decorator class. It is the core of the decorator design pattern. It contains an attribute for the type of interface. Instance is assigned dynamically at the creation of decorator using its constructor. Once assigned that instance method will be invoked.</p>
<pre class="brush: java;">
package com.javapapers.sample.designpattern;

abstract class IcecreamDecorator implements Icecream {

  protected Icecream specialIcecream;

  public IcecreamDecorator(Icecream specialIcecream) {
    this.specialIcecream = specialIcecream;
  }

  public String makeIcecream() {
    return specialIcecream.makeIcecream();
  }
}
</pre>
<p>Following two classes are similar. These are two decorators, concrete class implementing the abstract decorator. When the decorator is created the base instance is passed using the constructor and is assigned to the super class. In the makeIcecream method we call the base method followed by its own method addNuts(). This addNuts() extends the behavior by adding its own steps.</p>
<pre class="brush: java;">
package com.javapapers.sample.designpattern;

public class NuttyDecorator extends IcecreamDecorator {

  public NuttyDecorator(Icecream specialIcecream) {
    super(specialIcecream);
  }

  public String makeIcecream() {
    return specialIcecream.makeIcecream() + addNuts();
  }

  private String addNuts() {
    return &quot; + cruncy nuts&quot;;
  }
}
</pre>
<pre class="brush: java;">
package com.javapapers.sample.designpattern;

public class HoneyDecorator extends IcecreamDecorator {

  public HoneyDecorator(Icecream specialIcecream) {
    super(specialIcecream);
  }

  public String makeIcecream() {
    return specialIcecream.makeIcecream() + addHoney();
  }

  private String addHoney() {
    return &quot; + sweet honey&quot;;
  }
}
</pre>
<h3>Execution of the decorator pattern</h3>
<p>I have created a simple icecream and decorated that with nuts and on top of it with honey. We can use as many decorators in any order we want. This excellent flexibility and changing the behaviour of an instance of our choice at runtime is the main advantage of the decorator design pattern.</p>
<pre class="brush: java;">
package com.javapapers.sample.designpattern;

public class TestDecorator {

  public static void main(String args[]) {
    Icecream icecream = new HoneyDecorator(new NuttyDecorator(new SimpleIcecream()));
    System.out.println(icecream.makeIcecream());
  }

}
</pre>
<h3>Output</h3>
<pre class="brush: java;">
Base Icecream + cruncy nuts + sweet honey
</pre>
<h2>Decorator Design Pattern in java API</h2>
<p>java.io.BufferedReader;<br />
java.io.FileReader;<br />
java.io.Reader;</p>
<p>The above readers of java API are designed using decorator design pattern.</p>
]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/design-patterns/decorator-pattern/feed/</wfw:commentRss>
		<slash:comments>54</slash:comments>
		</item>
		<item>
		<title>Adapter Design Pattern</title>
		<link>http://javapapers.com/design-patterns/adapter-pattern/</link>
		<comments>http://javapapers.com/design-patterns/adapter-pattern/#comments</comments>
		<pubDate>Sat, 07 May 2011 00:01:41 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=523</guid>
		<description><![CDATA[An adapter helps two incompatible interfaces to work together. This is the real world definition for an adapter. Adapter design pattern is used when you want two different classes with incompatible interfaces to work together. The name says it all. Interfaces may be incompatible but the inner functionality should suit the need. In real world the [...]]]></description>
			<content:encoded><![CDATA[<p>An adapter helps two incompatible interfaces to work together. This is the real world definition for an adapter. Adapter design pattern is used when you want two different classes with incompatible interfaces to work together. The name says it all. Interfaces may be incompatible but the inner functionality should suit the need.</p>
<p>In real world the easy and simple example that comes to mind for an adapter is the travel power adapter. American socket and plug are different from British. Their <a title="Java interface" href="http://javapapers.com/core-java/abstract-and-interface-core-java-2/java-interface/">interface</a> are not compatible with one another. British plugs are cylindrical and American plugs are recangularish. You can use an adapter in between to fit an American (rectangular) plug in British (cylindrical) socket assuming voltage requirements are met with.</p>
<p><img class="alignright size-full wp-image-524" title="Adapter" src="http://javapapers.com/wp-content/uploads/2011/05/Adapter.jpg" alt="" width="297" height="239" /></p>
<h2>How to implement adapter design pattern?</h2>
<p>Adapter <a title="Introduction To Design Patterns" href="http://javapapers.com/design-patterns/introduction-to-design-patterns/">design pattern</a> can be implemented in two ways. One using the inheritance method and second using the <a href="http://javapapers.com/oops/association-aggregation-composition-abstraction-generalization-realization-dependency/">composition</a> method. Just the implementation methodology is different but the purpose and solution is same.</p>
<h3>Adapter implementation using inheritance</h3>
<p>When a class with incompatible method needs to be used with another class you can use inheritance to create an adapter class. The adapter class which is inherited will have new compatible methods. Using those new methods from the adapter the core function of the base class will be accessed. This is called &#8220;<a title="IS-A Relationship" href="http://javapapers.com/oops/association-aggregation-composition-abstraction-generalization-realization-dependency/">is-a</a>&#8221; relationship. The same real world example is implemented using java as below. Dont worry too much about logic, following example source code attempts to explain adapter design pattern and the goal is simplicity.</p>
<pre class="brush: java;">
public class CylindricalSocket {
	public String supply(String cylinStem1, String cylinStem1) {
		System.out.println(&quot;Power power power...&quot;);
	}
}

public class RectangularAdapter extends CylindricalSocket {
	public String adapt(String rectaStem1, Sting rectaStem2) {
		//some conversion logic
		String cylinStem1 = rectaStem1;
		String cylinStem2 = rectaStem2;
		return supply(cylinStem1, cylinStem2);
	}
}

public class RectangularPlug {
	private String rectaStem1;
	private String rectaStem2;
	public getPower() {
		RectangulrAdapter adapter = new RectangulrAdapter();
		String power = adapter.adapt(rectaStem1, rectaStem2);
		System.out.println(power);
	}
}
</pre>
<h3>Adapter implementation using composition</h3>
<p>The above implementation can also be done using composition. Instead of inheriting the base class create adapter by having the base class as attribute inside the adapter. You can access all the methods by having it as an attribute. This is nothing but &#8220;<a title="HAS-A Relationship" href="http://javapapers.com/oops/association-aggregation-composition-abstraction-generalization-realization-dependency/">has-a</a>&#8221; relationship. Following example illustrates this approach. Difference is only in the adapter class and other two classes are same. In most scenarios, prefer composition over inheritance. Using composition you can change the behaviour of class easily if needed. It enables the usage of tools like dependency injection.</p>
<pre class="brush: java;">
public class CylindricalSocket {
	public String supply(String cylinStem1, String cylinStem1) {
		System.out.println(&quot;Power power power...&quot;);
	}
}

public class RectangularAdapter {
	private CylindricalSocket socket;

	public String adapt(String rectaStem1, Sting rectaStem2) {
		//some conversion logic
		socket = new CylindricalSocket();
		String cylinStem1 = rectaStem1;
		String cylinStem2 = rectaStem2;
		return socket.supply(cylinStem1, cylinStem2);
	}
}

public class RectangularPlug {
	private String rectaStem1;
	private String rectaStem2;
	public getPower() {
		RectangulrAdapter adapter = new RectangulrAdapter();
		String power = adapter.adapt(rectaStem1, rectaStem2);
		System.out.println(power);
	}
}
</pre>
<h2>Adapter design pattern in java API</h2>
<p>java.io.InputStreamReader(InputStream)<br />
java.io.OutputStreamWriter(OutputStream)</p>
]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/design-patterns/adapter-pattern/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
	</channel>
</rss>

