<?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>Cyberward.net &#187; patterns</title>
	<atom:link href="http://www.cyberward.net/blog/tag/patterns/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cyberward.net/blog</link>
	<description>The Drive Failures and Shutter Clicks of Christopher Ward</description>
	<lastBuildDate>Mon, 03 Oct 2011 13:00:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Intro to Java Singleton Pattern</title>
		<link>http://www.cyberward.net/blog/2009/06/intro-to-java-singleton-pattern/</link>
		<comments>http://www.cyberward.net/blog/2009/06/intro-to-java-singleton-pattern/#comments</comments>
		<pubDate>Mon, 08 Jun 2009 21:53:37 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1273</guid>
		<description><![CDATA[The last pattern we looked at was the Adapter pattern. It was a good pattern to start with as it maps well to the physical world and is fairly simple. Now we will look at the Singleton pattern. In some respects it is the simplest of patterns, but there are some things to think about. [...]]]></description>
			<content:encoded><![CDATA[<p>The last pattern we looked at was the Adapter pattern. It was a good pattern to start with as it maps well to the physical world and is fairly simple. Now we will look at the Singleton pattern. In some respects it is the simplest of patterns, but there are some things to think about.</p>
<h3>The Singleton in the Physical World</h3>
<p>The idea behind the Singleton is to ensure that there can be only one (insert Highlander jokes here). If you had a factory that made widgets, you would want a widget to be created many many times. But there is only one factory. If you were modeling the US government, you would only want one president. Only one senate.</p>
<h3>The Singleton in the Software World</h3>
<p>On the software side, the idea is the same. It is usually used when we only want one set of configuration variables, one controller, one data base connection pool, that kind of thing.<br />
<span id="more-1273"></span></p>
<h3>How do we do this?</h3>
<p>Let&#8217;s back up a bit. Let us look at a very basic class that provides us with a code that is needed across our application.</p>
<pre lang="Java" name="MyClass.java" colla="+">
public class MyClass {

   private long code;

   public MyClass() {
      code = Calendar.getInstance().getTimeInMillis();
   }

   public long getCode() {
      return code;
   }
}
</pre>
<pre lang="Java" name="MyClassTest.java" colla="-">
public class MyClassTest {
   public static void main(String[] args) throws Exception {

      MyClass myClass1 = new MyClass();
      System.out.println(myClass1.getCode());

      Thread.sleep(500);// wait a bit to see if our code is the same

      MyClass myClass2 = new MyClass();
      System.out.println(myClass2.getCode());

      System.out.println("Oops. Different values.");
   }
}
</pre>
<p>If you only ever instantiated this class once, you are fine. But we haven&#8217;t done anything here to ensure that this is the case. There is nothing to stop someone from creating two MyClass objects.</p>
<p>Let&#8217;s start with the opposite. How do we create an instance of a class?</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1273code3'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p12733"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p1273code3"><pre class="java" style="font-family:monospace;">MyClass myClass1 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyClass<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
MyClass myClass2 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyClass<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>What can we do to ensure that only one instance can be created? Is there something else we have looked at that allows only one instance of a variable to occur? Static! We can use the static property.</p>
<pre lang="Java" name="MyStaticClass.java" colla="+">
public class MyStaticClass {

   private static long code = Calendar.getInstance().getTimeInMillis();

   public static long getCode() {
      return code;
   }
}
</pre>
<pre lang="Java" name="MyStaticClassTest.java" colla="-">
   public static void main(String[] args) throws Exception {

      MyStaticClass myClass1 = new MyStaticClass();
      System.out.println(MyStaticClass.getCode());
      System.out.println(myClass1);

      Thread.sleep(500);// wait a bit to make sure our code is the same

      MyStaticClass myClass2 = new MyStaticClass();
      System.out.println(MyStaticClass.getCode());
      System.out.println(myClass2);

      System.out.println("Ok. Same values.");
      System.out.println("Oops, different objects.");

   }
}
</pre>
<p>This time we have assigned a static variable our code, and provided a static method for accessing this code. Does this work? Somewhat. We only have one instance of code inside of MyStaticClass, but MyStaticClass is not guaranteed to have only one instance. This will get cumbersome to initialize as we add other data. It also results in a bunch of MyStaticClass.getCode() all over the application. What would be better would be to ask for this class just once, and then call getCode() as needed. How can we set that up?</p>
<h3>The Simplest Singleton</h3>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1273code4'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p12734"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code" id="p1273code4"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Singleton <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> Singleton singleton<span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> Singleton<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> Singleton getInstance<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span> singleton <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         singleton <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Singleton<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
      <span style="color: #000000; font-weight: bold;">return</span> singleton<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>This example doesn&#8217;t have our &#8220;code&#8221; in it, but it does show the elements of the singleton. We will add the &#8220;code&#8221; later.</p>
<p>There are some interesting things about this class. Look at the constructor. It is private! How does that work? We can&#8217;t do a &#8220;new&#8221; on this class! How can we create it? There is a private member variable that is static, and is of the same type as the class! It is a very strange sight at first glance. What is going on?</p>
<p>The constructor being private accounts for our first goal. No ability to call &#8220;new&#8221; on the object. If we can&#8217;t do a &#8220;new&#8221;, how can we create it? Well, we can do a &#8220;new&#8221;, but only from inside the class itself. We are doing that in the static getInstance() method. Look at what that method does. It first checks to see if an instance of the member variable singleton exists. If it doesn&#8217;t, it creates a &#8220;new&#8221; instance. This is the only place we will ever create an instance of the class Singleton. Therefore we have ensured that this is the only copy available. We then return singleton.</p>
<p>By doing things this way we have also lazy initialized the singleton. If we don&#8217;t need it, we never call getInstance(), and we never have to worry about the JVM allocating memory for something not used.</p>
<p>We also get a normal looking class out of it. We can have standard getters that are not static, and our application can pass this object around. It is easier to conceptualize the object used this way, and do maintenance later than a bunch of static methods seemingly randomly called within methods.</p>
<h3>Can we actually do something?</h3>
<p>Ok, I get your point. We need a bit more of an example. So here is a singleton with one &#8220;code&#8221; just like the others.</p>
<pre lang="Java" name="MySingletonClass.java" colla="+">
public class MySingletonClass {

   private static MySingletonClass singleton;

   private long code;

   private MySingletonClass() {
      code = Calendar.getInstance().getTimeInMillis();
   }

   public static MySingletonClass getInstance() {

      if ( singleton == null ) {
         singleton = new MySingletonClass();
      }
      return singleton;
   }

   public long getCode() {
      return code;
   }
}
</pre>
<pre lang="Java" name="MySingletonClassTest.java" colla="-">
public class MySingletonClassTest {
   public static void main(String[] args) throws Exception {

      MySingletonClass mySingletonClass1 = MySingletonClass.getInstance();
      System.out.println(mySingletonClass1.getCode());
      System.out.println(mySingletonClass1);

      Thread.sleep(500); //wait a bit to make sure our code is the same

      MySingletonClass mySingletonClass2 = MySingletonClass.getInstance();
      System.out.println(mySingletonClass2.getCode());
      System.out.println(mySingletonClass2);

      System.out.println("yea, same code");
      System.out.println("yea, same object");
   }
}
</pre>
<p>Look at that. Other than the singleton field, the constructor marked as private, and the getInstance() method, it is a pretty normal looking class. The constructor initializes our class just as we would expect. We can have pretty standard fields, like &#8220;code&#8221; with normal public getters.</p>
<h3>Is that all there is to it?</h3>
<p>Yup. It is that easy. Almost. Sometimes. There is one more wrinkle. Depending on how this singleton is being used, you may need to account for multiple threads. I am not going to get into that here, as we haven&#8217;t looked at threads yet. Keep in mind that if multiple objects could all call getInstance() at the same time, you may have an issue. Look it up, or wait and see if I get to threads eventually <img src='http://www.cyberward.net/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<h3>Why use the pattern?</h3>
<ul>
<li>Ensures only one instance of your code with minimal fuss.</li>
<li>The singleton can be assigned.</li>
<li>Uses lazy initialization to save memory.</li>
<li>It is proven. It works. You can try to avoid the pattern, but why bother?</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/06/intro-to-java-singleton-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Intro to Java Adapter Pattern</title>
		<link>http://www.cyberward.net/blog/2009/04/intro-to-java-adapter-pattern/</link>
		<comments>http://www.cyberward.net/blog/2009/04/intro-to-java-adapter-pattern/#comments</comments>
		<pubDate>Thu, 23 Apr 2009 20:00:47 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[adapter]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1074</guid>
		<description><![CDATA[In the last lesson we looked at patterns in general and why we might want to use them. So here is our first pattern. We are well on our way to creating a common language with which to talk design. One of the reasons I picked this pattern to start with, is that it is [...]]]></description>
			<content:encoded><![CDATA[<p>In the last lesson we looked at patterns in general and why we might want to use them. So here is our first pattern. We are well on our way to creating a common language with which to talk design.</p>
<p>One of the reasons I picked this pattern to start with, is that it is very easy to understand. It models real word situations very well, and that is what OO design is supposed to do right, model real world objects?</p>
<h3>The Adapter in the Physical World</h3>
<p>The concept of an Adapter is easy to understand. It does just what it is named to do. It adapts one object to that of another. Take the wall plug. It has three rectangular holes set at angles to fit the plug. It does? In Europe it does. We are traveling and need to plug our laptop into the wall. What do we use? An adapter.</p>
<h3>The Adapter in the Software World</h3>
<p>The idea is not so different in the software world. When you want to connect one class to another class that was not designed to fit together, you need an adapter class. Let&#8217;s look at an Java example to see how we can adapt one class to another.<br />
<span id="more-1074"></span></p>
<h3>Adapting an Animal</h3>
<p>In the last few lessons we have been dealing with the Animal interface. This is what it looked like:</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1074code10'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p107410"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code" id="p1074code10"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> Animal <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> move<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getName<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setName<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> pName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getType<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>We also had a BaseAnimal, but the idea was we were coding to this interface. So, keep in mind the speak() and move() methods. All the animals that we created implement these methods. What if we have a class that doesn&#8217;t implement Animal, but we want to treat as an Animal? For example, what if we found a really cool Reptile class out on the internet that we really wanted to use as an Animal, but it doesn&#8217;t implement our Animal interface. It doesn&#8217;t have speak() and move() methods. It has more specific methods hiss() and slither().</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1074code11'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p107411"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code" id="p1074code11"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Reptile <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">void</span> slither<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Reptile slithers.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">void</span> hiss<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Reptile hisses.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">void</span> snap<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Reptile snaps.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h3>Options?</h3>
<p>What can we do? What are our options? We could modify the code to have it implement the interface and change the method names to match our animal interface. That is probably a pattern that you have seen before, but it isn&#8217;t usually the best option.</p>
<p>What happens if the supplier, or coder of Reptile updates their code? Say, adds some code that improves the slithering? Every time you would have to install that class overtop of your changes, and then modify it again. That&#8217;s a lot of work. It usually means that upgrades don&#8217;t happen.</p>
<p>What happens if the supplier, or coder of Reptile only distributes a binary class? Are we SOL? Nope, Adapter to the rescue.</p>
<p>Take a look at this ReptileAnimalAdapter class:</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1074code12'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p107412"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code" id="p1074code12"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ReptileAnimalAdapter <span style="color: #000000; font-weight: bold;">extends</span> BaseAnimal <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> Reptile reptile<span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> ReptileAnimalAdapter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      reptile <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Reptile<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getType<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;reptile&quot;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> move<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      reptile.<span style="color: #006633;">slither</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      reptile.<span style="color: #006633;">hiss</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>What we have done, is use containment. The ReptileAnimalAdapter contains a Reptile. We don&#8217;t make any changes to Reptile, we just use it. Notice that it extends BaseAnimal, which implements Animal. Therefore, this Adapter meets all the requirements of our Animal interface contract. Look at the methods here. The ones we need to implement in here to finish the contract are getType(), move(), and speak(). We don&#8217;t change any methods on Reptile, we just adapt them to the Animal interface. When move is called, we call reptile.slither().</p>
<p>Let&#8217;s look at a class diagram of what we have now :</p>
<h3>Animal Adapter Class Diagram</h3>
<p><a href="http://www.cyberward.net/blog/wp-content/uploads/adapter.jpg"><img class="alignnone size-full" title="adapter class diagram" src="http://www.cyberward.net/blog/wp-content/uploads/adapter.jpg" alt="adapter class diagram" width="500" /></a></p>
<p>This diagram shows that a Reptile is contained within the ReptileAnimalAdapter that is extending the BaseAnimal class that is implementing the Animal interface.</p>
<h3>Does It Work?</h3>
<p>Take a look at AdapterTest1 to see how Reptile and ReptileAnimalAdapter work. This also shows how a ReptileAnimalAdapter &#8220;is a&#8221; Animal.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1074code13'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p107413"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
</pre></td><td class="code" id="p1074code13"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Test to look at our ReptileAnimalAdapter and see how it works. This will show
 * that we now have a &quot;new&quot; Animal type.
 *
 * @author Chris Ward 
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> AdapterTest1 <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// Show what a Reptile looks like</span>
      Reptile aReptile <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Reptile<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aReptile.<span style="color: #006633;">slither</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aReptile.<span style="color: #006633;">hiss</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// note: see that move is not a method on Reptile by uncommenting this</span>
      <span style="color: #666666; font-style: italic;">// aReptile.move();</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// Show that the ReptileAnimalAdapter can be used on it's own, and that</span>
      <span style="color: #666666; font-style: italic;">// it no longer has the &quot;slither&quot; method.</span>
      ReptileAnimalAdapter aAdapter <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ReptileAnimalAdapter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aAdapter.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aAdapter.<span style="color: #006633;">speak</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// note: see that slither is not a method on the adapter by uncommenting this</span>
      <span style="color: #666666; font-style: italic;">// aAdapter.slither();</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// Show that we now have a new animal that works just like any other Animal</span>
      Animal aAnimal <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ReptileAnimalAdapter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aAnimal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aAnimal.<span style="color: #006633;">speak</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>AdapterListTest1 also shows how ReptileAnimalAdapter &#8220;is a&#8221; Animal, by putting it in a Java5 Animal Typed list.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1074code14'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p107414"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
</pre></td><td class="code" id="p1074code14"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * This test just shows that we can take our ReptileAnimalAdapter and add it to
 * a list of Animals, and use them as if they were simple Animals that move and speak.
 *
 * @author Chris Ward 
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> AdapterListTest1 <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> pArgs<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// using Java 5 typed list. Only objects of type</span>
      <span style="color: #666666; font-style: italic;">// Animal can go in this list.</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> animalList <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// if we don't need references to the animals</span>
      <span style="color: #666666; font-style: italic;">// we create, don't create local variables for them.</span>
      animalList.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      animalList.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      animalList.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> ReptileAnimalAdapter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Moving animals:&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// use a Java 5 &quot;for each&quot; loop to minimize typing.</span>
      <span style="color: #666666; font-style: italic;">// using Java 5 typed lists we don't need casting.</span>
      <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>Animal aAnimal <span style="color: #339933;">:</span> animalList<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         <span style="color: #666666; font-style: italic;">// we don't need to know what type of animal</span>
         <span style="color: #666666; font-style: italic;">// we are moving, just that we want them to move.</span>
         aAnimal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
&nbsp;
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Getting animals to speak:&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// we don't need to know what type of animal</span>
      <span style="color: #666666; font-style: italic;">// is speaking, just that we want them to speak.</span>
      <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>Animal aAnimal <span style="color: #339933;">:</span> animalList<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         aAnimal.<span style="color: #006633;">speak</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h3>Review what we did.</h3>
<p>So, what have we done with this adapter? Nothing new really. We have used some of the Java principles that we have talked about in a particular way, and called it applying the Adapter pattern. That is all that using patterns is.</p>
<ol>
<li>We created a new class (ReptileAnimalAdapter) that extends a base class, or implements an interface, (BaseAnimal in this case) and call it an Adapter.</li>
<li>We used containment to hold an instance of the class we need to adapt. (Reptile)</li>
<li>We coded to the interface (of Animal), to adapt the methods of Animal to Reptile.</li>
</ol>
<p>That&#8217;s it. Nothing too complicated or convoluted. Some of the patterns are more complicated than this one, but several are simple. The point, is that you now understand a pattern. The next step is learning to recognize the pattern when you see it, and learning when to use it when presented with a problem.</p>
<p>Now when someone says, &#8220;Hey, I found a cool FlyingFish class! Can we use it with our code?&#8221;. You can respond with &#8220;Sure, we just need an Adapter class!&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/04/intro-to-java-adapter-pattern/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Intro to Java Patterns</title>
		<link>http://www.cyberward.net/blog/2009/04/intro-to-java-patterns/</link>
		<comments>http://www.cyberward.net/blog/2009/04/intro-to-java-patterns/#comments</comments>
		<pubDate>Tue, 21 Apr 2009 20:39:59 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1059</guid>
		<description><![CDATA[Patterns are a very important part of Java. They allow us to speak a common language. The names can be misused, and thrown around by people trying to sound important, but they really do help us to be able to communicate ideas between us. It does take some Java knowledge to be able to read, [...]]]></description>
			<content:encoded><![CDATA[<p>Patterns are a very important part of Java. They allow us to speak a common language. The names can be misused, and thrown around by people trying to sound important, but they really do help us to be able to communicate ideas between us.</p>
<p>It does take some Java knowledge to be able to read, use and apply patterns, but I think we have seen enough Java and OO principles to start looking at patterns. It is good to start hearing about and seeing different patterns at any level of Java programming.</p>
<p>So what is a pattern? In the physical world, it would be a series of steps taken over and over again that could be written down and repeated. In the software world, it is not really a set of steps, but a software solution that people apply over and over again in their coding. Experienced developers have put these solutions together, and given their pattern a name. By looking at and studying patterns, we can take advantage of the experience of others, and learn from their solutions. One interesting thing about patterns, is that they don&#8217;t need to be language specific. If you learn about the Adapter or the Command pattern, you can apply that pattern to PHP, Ruby, or Java.<br />
<span id="more-1059"></span></p>
<h3>Resources</h3>
<p>One of the original books on the topic is by the Gang of Four: Design Patterns: Elements of Reusable Object-Oriented Software (<a href=" http://www.amazon.com/gp/product/0201633612/">Amazon</a>)</p>
<p>Sun on J2EE design patterns: <a href="http://java.sun.com/developer/technicalArticles/J2EE/patterns/">http://java.sun.com/developer/technicalArticles/J2EE/patterns/</a></p>
<p>A list of common Java design patterns: <a href="http://www.fluffycat.com/Java-Design-Patterns/">http://www.fluffycat.com/Java-Design-Patterns/</a></p>
<h3>Head First Design Patterns</h3>
<p>If you would like a paper copy of something, I would recommend the Head First Design Patterns book. It&#8217;s by Freeman &amp; Freeman, published by O&#8217;Reilly. (<a href="http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124/">Amazon</a>) This is a good book that doesn&#8217;t assume a high level of java knowledge (at least at the beginning) but does a great job of explaining patterns. It uses Java for the examples, and the different patterns often build on each other. Well worth a read for all levels of programmers.</p>
<h3>Q &amp; A Session</h3>
<p>Q: What am I supposed to ask questions about?<br />
A: Patterns. Anything that you want to ask about patterns is fair game.</p>
<p>Q: Well, don&#8217;t people just learn the pattern names so they can throw them around to sound important?<br />
A: I hope not, but I am sure some people do. When we all learn patterns, it makes it easier to talk about designing code. When someone is helping you, and you both understand some patterns, it is easier to communicate.</p>
<p>Q: But can&#8217;t people just explain what they mean. Don&#8217;t we have enough acronyms and buzzwords already?<br />
A: I sense that patterns make you nervous, but don&#8217;t be. Think of it this way. When someone says they FedEx something, we know what the steps they went through. They wrapped the package, dropped it off, FedEx picked it up, flew it across the country, put it in a truck, and delivered it. When someone says &#8220;I Googled it&#8221;, we know what they did. They used a computer, with a web browser, at Google&#8217;s site, to search the internet for something.</p>
<p>Q: Yea, Ok, but everyone knows what FedEx and Google are, not everyone knows patterns.<br />
A: Bingo. Now your making my point. You now see the value when people understand a common language. All I am suggesting is that we all try to improve our language skills to make it easier to communicate.</p>
<p>Q: Alright, maybe it is a good idea to learn a few of them. Where did they come from anyway?<br />
A: People have always looked to more experienced coders for help. It is likely that experienced people have already run across similar problems and found a good way to fix them. Kind of like keeping a tool box of solutions in your back pocket.</p>
<p>Q: So, then Patterns are just random code examples that people have collected?<br />
A: No, they are more basic than that. One of the best early attempts to collect patterns into a published work was by the Gang of Four mentioned earlier. They recognized that there were clearly defined solutions to problems that could be applied to almost any computer language.</p>
<p>Q: Almost any computer language?<br />
A: Patterns usually focus on object orientated design principles, like those that we have talked about in earlier sessions. Some of the patterns are much harder to apply to languages that don&#8217;t use objects.</p>
<p>Q: Learning about Patterns is just building on what we have been learning?<br />
A: Exactly. We have talked about objects, classes, interfaces, abstract classes, containment, and inheritance. We will use all of these ideas and principles as we look at patterns.</p>
<p>Q: Ok, so if Patterns are so great, why haven&#8217;t you brought it up yet?<br />
A: I have. Remember the last unit, on Reflection? We talked about a Factory. Guess what? That is a pattern. We just hadn&#8217;t named it as one.</p>
<p>Q: Cool. These aren&#8217;t so bad.<br />
A: Alright, are you ready to look at some more then?</p>
<p>Q: Wait a minute. I was just skimming the Head First Design Patterns book. Don&#8217;t they use the Q&amp;A thing in there a lot? Did you steal that idea?<br />
A: I didn&#8217;t steal it. I just applied the Pattern.</p>
<p>Q: Ok, fine. What&#8217;s first?<br />
A: The next pattern we will look at is the Adapter Pattern.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/04/intro-to-java-patterns/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

