<?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, 05 Feb 2012 15:25:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.2</generator>
		<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 Patter</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 Abstract 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>5</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>13</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>41</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>17</slash:comments>
		</item>
		<item>
		<title>Singleton Design Pattern</title>
		<link>http://javapapers.com/design-patterns/singleton-pattern/</link>
		<comments>http://javapapers.com/design-patterns/singleton-pattern/#comments</comments>
		<pubDate>Mon, 02 May 2011 00:01:18 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=517</guid>
		<description><![CDATA[Singleton design pattern is the first design pattern I learned (many years back). In early days when someone asks me, &#8220;do you know any design pattern?&#8221; I quickly and promptly answer &#8220;I know singleton design pattern&#8221; and the question follows, &#8220;do you know anything other than singleton&#8221; and I stand stumped! A java beginner will [...]]]></description>
			<content:encoded><![CDATA[<p>Singleton design pattern is the first <a title="Introduction To Design Patterns" href="http://javapapers.com/design-patterns/introduction-to-design-patterns/">design pattern</a> I learned (many years back). In early days when someone asks me, &#8220;do you know any design pattern?&#8221; I quickly and promptly answer &#8220;I know singleton design pattern&#8221; and the question follows, &#8220;do you know anything other than singleton&#8221; and I stand stumped!</p>
<div><img class="alignright size-full wp-image-518" title="singleegg" src="http://javapapers.com/wp-content/uploads/2011/04/singleegg.jpg" alt="" width="300" height="359" /></div>
<p>A java beginner will know about singleton design pattern. At least he will think that he knows singleton pattern. The definition is even easier than Newton&#8217;s third law. Then what is special about the singleton pattern. Is it so simple and straightforward, does it even deserve an article? Do you believe that you know 100% about singleton design pattern? If you believe so and you are a beginner read through the end, there are surprises for you.</p>
<p>There are only two points in the definition of a singleton design pattern,</p>
<ol>
<li>there should be only one instance allowed for a class and</li>
<li>we should allow global point of access to that single instance.</li>
</ol>
<p>GOF says, &#8220;Ensure a class has only one instance, and provide a global point of access to it. [GoF, p127]&#8220;.</p>
<p>The key is not the problem and definition. In singleton pattern, trickier part is implementation and management of that single instance. Two points looks very simple, is it so difficult to implement it. Yes it is very difficult to ensure &#8220;single instance&#8221; rule, given the flexibility of the APIs and many flexible ways available to access an instance. Implementation is very specific to the language you are using. So the security of the single instance is specific to the language used.</p>
<h2>Strategy for Singleton instance creation</h2>
<p>We suppress the constructor and don&#8217;t allow even a single instance for the class. But we declare an attribute for that same class inside and create instance for that and return it. <a title="Factory Design Pattern" href="http://javapapers.com/design-patterns/abstract-factory-pattern/">Factory design pattern</a> can be used to create the singleton instance.</p>
<pre class="brush: java;">
package com.javapapers.sample.designpattern;
public class Singleton {
	private static Singleton singleInstance;
		private Singleton() {}
	public static Singleton getSingleInstance() {
		if (singleInstance == null) {
			synchronized (Singleton.class) {
				if (singleInstance == null) {
					singleInstance = new Singleton();
				}
			}
		}
		return singleInstance;
	}
</pre>
<p>You need to be careful with multiple threads. If you don&#8217;t synchronize the method which is going to return the instance then, there is a possibility of allowing multiple instances in a multi-threaded scenario. Do the synchronization at block level considering the performance issues. In the above example for singleton pattern, you can see that it is threadsafe.</p>
<h2>Early and lazy instantiation in singleton pattern</h2>
<p>The above example code is a sample for lazy instantiation for singleton design pattern. The single instance will be created at the time of first call of the getSingleInstance() method. We can also implement the same singleton design pattern in a simpler way but that would instantiate the single instance early at the time of loading the class. Following example code describes how you can instantiate early. It also takes care of the multithreading scenario.</p>
<pre class="brush: java;">
package com.javapapers.sample.designpattern;
public class Singleton {
	private static Singleton singleInstance = new Singleton();
	private Singleton() {}
	public static Singleton getSingleInstance() {
		return singleInstance;
	}
}
</pre>
<h2>Singleton and Serialization</h2>
<p>Using <a title="Java Serialization" href="http://javapapers.com/core-java/java-serialization/">serialization</a>, single instance contract of the singleton pattern can be violated. You can serialize and de-serialize and get a new instance of the same singleton class. Using java api, you can implement the below method and override the instance read from the stream. So that you can always ensure that you have single instance.</p>
<pre class="brush: java;">ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;</pre>
<p>This article is an attempt to explain the basics on singleton design pattern. If you want more insight on singleton refer this technical article &#8220;<a href="http://java.sun.com/developer/technicalArticles/Programming/singletons/">When is a Singleton not a Singleton?</a>&#8221; and its references.</p>
<h2>Usage of Singleton Patter in Java API</h2>
<p>java.lang.Runtime#getRuntime()  java.awt.Desktop#getDesktop()</p>
]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/design-patterns/singleton-pattern/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>Prototype Design Pattern</title>
		<link>http://javapapers.com/design-patterns/prototype-pattern/</link>
		<comments>http://javapapers.com/design-patterns/prototype-pattern/#comments</comments>
		<pubDate>Wed, 14 Jul 2010 12:04:27 +0000</pubDate>
		<dc:creator>Joe</dc:creator>
				<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://javapapers.com/?p=371</guid>
		<description><![CDATA[When creating an object is time consuming and a costly affair and you already have a most similar object instance in hand, then you go for prototype pattern. Instead of going through a time consuming process to create a complex object, just copy the existing similar object and modify it according to your needs. Its [...]]]></description>
			<content:encoded><![CDATA[<p>When creating an object is time consuming and a costly affair and you already have a most similar object instance in hand, then you go for prototype pattern. Instead of going through a time consuming process to create a complex object, just copy the existing similar object and modify it according to your needs.</p>
<p>Its a simple and straight forward design pattern. Nothing much hidden beneath it. If you don&#8217;t have much experience with enterprise grade huge application, you may not have experience in creating a complex / time consuming instance. All you might have done is use the new operator or inject and instantiate.</p>
<p>If you are a beginner you might be wondering, why all the fuss about prototye design pattern and do we really need this <a title="Introduction To Design Patterns" href="http://javapapers.com/design-patterns/introduction-to-design-patterns/">design pattern</a>? Just ignore, all the big guys requires it. For you, just understand the pattern and sleep over it. You may require it one day in future.<img class="alignright size-full wp-image-372" title="prototype" src="http://javapapers.com/wp-content/uploads/2010/07/prototype.gif" alt="" width="294" height="294" /></p>
<p>Prototype pattern may look similar to<a title="Builder Design Pattern" href="http://javapapers.com/design-patterns/builder-pattern/"> builder design pattern</a>. There is a huge difference to it. If you remember, &#8220;the same construction process can create different representations&#8221; is the key in builder pattern. But not in the case of prototype pattern.</p>
<p>So, how to implement the prototype design pattern? You just have to copy the existing instance in hand. When you say copy in java, immediately cloning comes into picture. Thats why when you read about prototype pattern, all the literature invariably refers java cloning.</p>
<p>Simple way is, clone the existing instance in hand and then make the required update to the cloned instance so that you will get the object you need. Other way is, tweak the cloning method itself to suit your new object creation need. Therefore whenever you clone that object you will directly get the new object of desire without modifying the created object explicitly.</p>
<p>The prototype design pattern mandates that the instance which you are going to copy should provide the copying feature. It should not be done by an external utility or provider.</p>
<p>But the above, other way comes with a caution. If somebody who is not aware of your tweaking the clone business logic uses it, he will be in issue. Since what he has in hand is not the exact clone. You can go for a custom method which calls the clone internally and then modifies it according to the need. Which will be a better approach.</p>
<p>Always remember while using clone to copy, whether you need a <a title="Java Clone, Shallow Copy and Deep Copy" href="http://javapapers.com/core-java/java-clone-shallow-copy-and-deep-copy/">shallow copy or deep copy</a>. Decide based on your business needs. If you need a deep copy, you can use serialization as a hack to get the deep copy done. Using clone to copy is entirey a design decision while implementing the prototype design pattern. Clone is not a mandatory choice for prototype pattern.</p>
<p>In prototype pattern, you should always make sure that you are well knowledgeable about the data of the object that is to be cloned. Also make sure that instance allows you to make changes to the data. If not, after cloning you will not be able to make required changes to get the new required object.</p>
<p>Following sample java source code demonstrates the prototype pattern. I have a basic bike in hand with four gears. When I want to make a different object, an advance bike with six gears I copy the existing instance. Then make necessary modifications to the copied instance. Thus the prototype pattern is implemented. Example source code is just to demonstrate the design pattern, please don&#8217;t read too much out of it. I wanted to make things as simple as possible.</p>
<h2>Sample Java Source Code for Prototype Design Pattern</h2>
<pre class="brush: java;">
package com.javapapers.sample.designpattern.prototype;

class Bike implements Cloneable {
	private int gears;
	private String bikeType;
	private String model;
	public Bike() {
		bikeType = &quot;Standard&quot;;
		model = &quot;Leopard&quot;;
		gears = 4;
	}

	public Bike clone() {
		return new Bike();
	}

	public void makeAdvanced() {
		bikeType = &quot;Advanced&quot;;
		model = &quot;Jaguar&quot;;
		gears = 6;
	}
	public String getModel(){
		return model;
	}
}

public class Workshop {
	public Bike makeJaguar(Bike basicBike) {
		basicBike.makeAdvanced();
		return basicBike;
	}
	public static void main(String args[]){
		Bike bike = new Bike();
		Bike basicBike = bike.clone();
		Workshop workShop = new Workshop();
		Bike advancedBike = workShop.makeJaguar(basicBike);
		System.out.println(&quot;Prototype Design Pattern: &quot;+advancedBike.getModel());
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://javapapers.com/design-patterns/prototype-pattern/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>

