<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<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/"
	>

<channel>
	<title>singleton-pattern &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/singleton-pattern/</link>
	<description>Feed of posts on WordPress.com tagged "singleton-pattern"</description>
	<pubDate>Sun, 27 Dec 2009 10:58:13 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Singleton in .NET]]></title>
<link>http://dotnetpal.wordpress.com/2009/12/23/singleton-in-net/</link>
<pubDate>Wed, 23 Dec 2009 10:08:48 +0000</pubDate>
<dc:creator>dotnetpal</dc:creator>
<guid>http://dotnetpal.wordpress.com/2009/12/23/singleton-in-net/</guid>
<description><![CDATA[There are some instances when we need only single object of class. For example MDI form is always ha]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>There are some instances when we need only single object of class. For example MDI form is always has single object. For this we need to restrict class to create multiple objects. For this we can use private constructor. Class having private constructor cannot instantiate. In other word, we cannot create object of class.</p>
<p>The declaration of empty constructor is prevents the declaration of <strong>default constructor</strong>. If you are not giving any access modifier of with the constructor its by default private.</p>
<p>Now how you stop creating more than one object of class. With the help of private constructor you can achieve this functionality.</p>
<pre>    public class SingletonClass
    {
        int i;
        static SingletonClass objSingletonClass;
        private SingletonClass()
        {
            i = 10;
        }

        public static SingletonClass getInstance()
        {
            if (objSingletonClass == null)
            {
                objSingletonClass = new SingletonClass();
            }
            return objSingletonClass;
        }

        public int getValue()
        {
            return i;
        }
    }</pre>
<p>In this code, I am creating <strong>private constructor of class</strong>. Now problem is that how I create instance of class if I had created private constructor. To solve this problem I had create static method getInstance(). In this method I am returning instance of static class object. The pattern I am using for creating object is singleton.</p>
<p><strong>Singleton pattern</strong> ensures a class has only single instance, and provide a global point of access to it.</p>
<p>For download of code please fo to below link</p>
<p><a href="http://www.dotnetpal.com/pattern/singleton.htm">http://www.dotnetpal.com/pattern/singleton.htm</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[The singleton manager class]]></title>
<link>http://incomod.wordpress.com/2009/12/16/the-singleton-manager-class/</link>
<pubDate>Wed, 16 Dec 2009 21:46:24 +0000</pubDate>
<dc:creator>Kos</dc:creator>
<guid>http://incomod.wordpress.com/2009/12/16/the-singleton-manager-class/</guid>
<description><![CDATA[Notice: This class is not for public usage and is subject to change. &lt;?php /** * Retrieve a refer]]></description>
<content:encoded><![CDATA[Notice: This class is not for public usage and is subject to change. &lt;?php /** * Retrieve a refer]]></content:encoded>
</item>
<item>
<title><![CDATA[ The ActionScript 3 Simpler Singleton Pattern]]></title>
<link>http://python2.wordpress.com/2009/08/07/the-actionscript-3-simpler-singleton-pattern/</link>
<pubDate>Fri, 07 Aug 2009 13:29:37 +0000</pubDate>
<dc:creator>raychorn</dc:creator>
<guid>http://python2.wordpress.com/2009/08/07/the-actionscript-3-simpler-singleton-pattern/</guid>
<description><![CDATA[What could be more Agile than a Simpler Singleton requiring far less code that any other Singleton P]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>What could be more Agile than a Simpler Singleton requiring far less code that any other Singleton Pattern you may have heard about ?</p>
<div>
<div>
<h2><a title="Permanent Link to The ActionScript 3 Singleton Pattern Debunked !" rel="bookmark" href="http://blog.vyperlogix.com/index.php/2009/08/06/the-actionscript-3-singleton-pattern-debunked/">The ActionScript 3 Singleton Pattern Debunked !</a></h2>
<p>(FYI – <em>The link presented here in the text of this post takes you to the original Blog Article… Click the links, always click the links… Can’t see the content if you don’t click the links… Right ?!?</em>)</p>
<p>Follow the links to get the source.</p>
<p>This Singleton Design Pattern can be adapted to work with any language that handles Classes in the same manner as ActionScript 3 (<em>Class files are imported only once regardless of how many modules actually import the Class file</em>).</div>
</div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Singleton pattern generic code - example from C# 3.0 Design Patterns]]></title>
<link>http://spolnik.wordpress.com/2009/07/19/singleton-pattern-generic-code-example-from-c-3-0-design-patterns/</link>
<pubDate>Sun, 19 Jul 2009 08:36:34 +0000</pubDate>
<dc:creator>Jacek Spólnik</dc:creator>
<guid>http://spolnik.wordpress.com/2009/07/19/singleton-pattern-generic-code-example-from-c-3-0-design-patterns/</guid>
<description><![CDATA[Role One way solution for achieving reusability of the Singleton Pattern Implementation using System]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><h3>Role</h3>
<p>One way solution for achieving reusability of the Singleton Pattern</p>
<h3>Implementation</h3>
<pre class="brush: csharp;">
using System;

namespace SingletonPatternGenericCode
{
    public class Singleton&lt;T&gt; where T : class, new()
    {
        private Singleton()
        {
        }

        public static T UniqueInstance
        {
            get { return SingletonCreator.Instance; }
        }

        #region Nested type: SingletonCreator

        private class SingletonCreator
        {
            internal static readonly T Instance = new T();

            static SingletonCreator()
            {
            }
        }

        #endregion
    }

    internal class Test1
    {
    }

    internal class Test2
    {
    }

    public class Client
    {
        public static void Main()
        {
            Test1 t1A = Singleton&lt;Test1&gt;.UniqueInstance;
            Test2 t2A = Singleton&lt;Test2&gt;.UniqueInstance;
            Test1 t1B = Singleton&lt;Test1&gt;.UniqueInstance;

            if (!Equals(t1A, t2A))
            {
                Console.WriteLine(&quot;t1a and t2a objects are different&quot;);
            }

            if (Equals(t1A, t1B))
            {
                Console.WriteLine(&quot;t1a and t2a objects are the same instance&quot;);
            }
        }
    }
}
</pre>
<h3>Output:</h3>
<address>t1a and t2a objects are different<br />
t1a and t2a objects are the same instance</address>
<address> </address>
<h3><span style="display:block;"><span>Bibliography</span></span></h3>
<ul>
<li><a href="http://patterns.cs.up.ac.za/" target="_blank">C# Design Patterns</a></li>
</ul>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Design patterns in C# - part 10 (Singleton pattern)]]></title>
<link>http://spolnik.wordpress.com/2009/07/19/design-patterns-in-c-part-10-singleton-pattern/</link>
<pubDate>Sun, 19 Jul 2009 08:11:26 +0000</pubDate>
<dc:creator>Jacek Spólnik</dc:creator>
<guid>http://spolnik.wordpress.com/2009/07/19/design-patterns-in-c-part-10-singleton-pattern/</guid>
<description><![CDATA[Role The purpose of the Singleton pattern is to endure that there is only one instance of a class, a]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><h3>Role</h3>
<p>The purpose of the Singleton pattern is to endure that there is only one instance of a class, and that there is a global access point to that object.</p>
<h3>Design</h3>
<p><img class="alignnone size-full wp-image-172" title="SingletonPattern" src="http://spolnik.wordpress.com/files/2009/07/singletonpattern.jpg" alt="SingletonPattern" width="331" height="213" /></p>
<h3>Implementation</h3>
<ul>
<li>Singleton -&#62; Facade</li>
</ul>
<pre class="brush: csharp;">
namespace FacadePattern
{
    public interface IFacade
    {
        void OperationFirst();
        void OperationSecond();
        void OperationThird();
    }

    public interface ISystem
    {
        void A();
        void B();
    }
}
</pre>
<pre class="brush: csharp;">
using System;

namespace FacadePattern
{
    internal class SystemOne : ISystem
    {
        #region ISystem Members

        public void A()
        {
            Console.WriteLine(&quot;Operation A in SystemOne !&quot;);
        }

        public void B()
        {
            Console.WriteLine(&quot;Operation B in SystemOne !&quot;);
        }

        #endregion
    }

    internal class SystemTwo : ISystem
    {
        #region ISystem Members

        public void A()
        {
            Console.WriteLine(&quot;Operation A in SystemTwo !&quot;);
        }

        public void B()
        {
            Console.WriteLine(&quot;Operation B in SystemTwo !&quot;);
        }

        #endregion
    }
}
</pre>
<pre class="brush: csharp;">
namespace FacadePattern
{
    public class Facade : IFacade
    {
        private readonly SystemOne _systemOne;
        private readonly SystemTwo _systemTwo;

        private Facade()
        {
            this._systemOne = new SystemOne();
            this._systemTwo = new SystemTwo();
        }

        public static Facade Instance
        {
            get { return SingletonCreator.Instance; }
        }

        #region IFacade Members

        public void OperationFirst()
        {
            this._systemOne.A();
            this._systemTwo.B();
        }

        public void OperationSecond()
        {
            this._systemTwo.A();
        }

        public void OperationThird()
        {
            this._systemOne.B();
        }

        #endregion

        #region Nested type: SingletonCreator

        private class SingletonCreator
        {
            static SingletonCreator() {}
            internal static readonly Facade Instance = new Facade();
        }

        #endregion
    }
}
</pre>
<pre class="brush: csharp;">
using System;

namespace FacadePattern
{
    public class TestFacadePattern
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(&quot;Operation first of facade singleton: &quot;);
            Facade.Instance.OperationFirst();
            Console.WriteLine(&quot;Operation second of facade singleton: &quot;);
            Facade.Instance.OperationSecond();
            Console.WriteLine(&quot;Operation third of facade singleton: &quot;);
            Facade.Instance.OperationThird();
        }
    }
}
</pre>
<p><strong>OUTPUT:</strong></p>
<address>Operation first of facade singleton:<br />
Operation A in SystemOne !<br />
Operation B in SystemTwo !<br />
Operation second of facade singleton:<br />
Operation A in SystemTwo !<br />
Operation third of facade singleton:<br />
Operation B in SystemOne !</address>
<address> </address>
<h3>Use when</h3>
<ul>
<li>You need to ensure there is only one instance of a class.</li>
<li>Controlled access to that instance is essential.</li>
<li>You might need more than one instance at a later stage.</li>
<li>The control should be localized in the instantiated class, not in some other mechanism.</li>
</ul>
<h3><span style="display:block;"><span>Bibliography</span></span></h3>
<ul>
<li>Erich Gamma et al. Design Patterns</li>
<li><a href="http://patterns.cs.up.ac.za/" target="_blank">C# Design Patterns</a></li>
</ul>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Code Injection und Siemens Gigaset WLAN Repeater]]></title>
<link>http://devjta.wordpress.com/2009/03/25/code-injection-und-siemens-gigaset-wlan-repeater/</link>
<pubDate>Wed, 25 Mar 2009 08:57:07 +0000</pubDate>
<dc:creator>devjta</dc:creator>
<guid>http://devjta.wordpress.com/2009/03/25/code-injection-und-siemens-gigaset-wlan-repeater/</guid>
<description><![CDATA[Aufgrund einer Diskussion um das Singleton Pattern im Java-Forum (siehe hier: Umfrage zu Singletons ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Aufgrund einer Diskussion um das <a href="http://de.wikipedia.org/wiki/Singleton_(Entwurfsmuster)" target="_blank">Singleton Pattern</a> im <a href="http://www.java-forum.org/" target="_blank">Java-Forum</a> (siehe hier: <a href="http://www.java-forum.org/softwareentwicklung/80674-singletons-sind.html" target="_blank">Umfrage zu Singletons</a> und hier: <a href="http://www.java-forum.org/java-basics-anfaenger-themen/80630-denkfehler-singleton.html" target="_blank">Denkfehler Singleton</a>) habe ich mich mal mit Code Injection beschäftigt.     <br />Daraus entstand dieser Blog Eintrag von mir im Java-Forum: <a href="http://www.java-forum.org/blogs/the_29/29-code-injuction-mit-google-guice.html" target="_blank">Code Injection.</a></p>
<p>Dann habe ich gestern ein weiteres Hardwareteil für meine Dreambox erhalten. Und zwar den <a href="http://geizhals.at/a124537.html" target="_blank">Siemens Gigaset WLAN Repeater</a>. Diesen kann man auf einen Ethernet Adapter umstellen, sodass meine Dreambox 100 dann einen WLAN Zugriff bekommt.</p>
<p>Leider ist die Einstellung über die GUI recht verwirrend. Die Umstellung auf den Modus: Ethernet Adapter ist zwar recht einfach, aber wie man sich zu einem WLAN verbindet dann nicht mehr.    <br />Man stellt das ganze so ein, als würde man ein WLAN betreiben. Also SSID vergeben und dann die Verschlüsselung auswählen sowie das Passwort. Dann verbindet sich das Siemens Teil automatisch mit diesem WLAN (sieht man auch, da dann das WLAN Licht leuchtet).</p>
<p>Ich war am Anfang verwirrt, da mein anderer Ethernet Adapter <a href="http://www.linksysbycisco.com/DE/de/support/WET11" target="_blank">Linksys WET-11</a> über die Weboberfläche das WLAN einfach auszuwählen war. Leider kann der nur WEP und deswegen habe ich mir das Siemens Teil gekauft.    <br />Habe es dann am Abend mit dem <a href="http://www.apple.com/at/macbook/" target="_blank">Macbook</a> probiert und es hat problemlos funktioniert.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Singleton pattern]]></title>
<link>http://teofilachirei.wordpress.com/2009/03/18/singleton-pattern/</link>
<pubDate>Wed, 18 Mar 2009 21:29:29 +0000</pubDate>
<dc:creator>Teofil Achirei</dc:creator>
<guid>http://teofilachirei.wordpress.com/2009/03/18/singleton-pattern/</guid>
<description><![CDATA[Let&#8217;s pause developing our simple serial focused web crawler and discuss about the singleton p]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Let&#8217;s pause developing our <strong>simple serial focused web crawler</strong> and discuss about <strong>the singleton pattern</strong>. You will find this post very useful for our little crawler.<br />
So, if you haven&#8217;t heard about <strong>design patterns</strong>, I recommend you to read a little on Wikipedia:<br />
<a href="http://en.wikipedia.org/wiki/Design_pattern_(computer_science)">http://en.wikipedia.org/wiki/Design_pattern_(computer_science)</a>.</p>
<p>The <strong>singleton pattern</strong> (<a href="http://en.wikipedia.org/wiki/Singleton_pattern">more on Wikipedia</a>) is a very simple and useful pattern.</p>
<p>There are many cases when we need <strong>an instance</strong> from a class (an object) but we kind of need it to be <strong>the same instance</strong>. If it doesn&#8217;t seem obvious, just think about the display driver (or any kind of driver) or the <strong><a href="http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Graphics.html">Graphics</a></strong> object.</p>
<p>In many cases, the singleton pattern can be replaced by using an <strong>utility class</strong>: a class with <strong>public static</strong> methods.</p>
<p>But, in some circumstances, we need <strong>the same object</strong> which means <strong>an instance</strong></p>
<p>Let&#8217;s take a look at the following example.</p>
<pre class="brush: java;">
package ro.teo.singletonexample;

public class MyIncrement {
   private int i;
   public MyIncrement(){
      i=0;
   }
   public int nextVal(){
      i++;
      return i;
   }
}
</pre>
<pre class="brush: java;">
package ro.teo.singletonexample;

public class SomeInc {
   public void doStuff(MyIncrement mi){
      System.out.println(&quot;I do some serious stuff ...&quot;);
      int v=mi.nextVal();
      System.out.println(v);
   }
}
</pre>
<pre class="brush: java;">
package ro.teo.singletonexample;

public class SEMain {
  public static void main(String[] args){
    MyIncrement mi1=new MyIncrement();
    MyIncrement mi2=new MyIncrement();

    SomeInc si1=new SomeInc();
    SomeInc si2=new SomeInc();

    for (int i=0;i&amp;#60;10;i++){
      mi1.nextVal();
    }
    for (int i=0;i&amp;#60;4;i++){
      mi2.nextVal();
    }

    si1.doStuff(mi1);
    si2.doStuff(mi2);
  }
}
</pre>
<p>Let&#8217;s see the output:</p>
<pre style="font-size:9pt;border:1px black solid;background-color:#EEEEEE;padding:3px;">
I do some serious stuff ...
11
I do some serious stuff ...
5
</pre>
<p>As you can see, the result of using 2 <strong>different instances</strong> is obvious.<br />
Of course, we could just use the same <u>mi1</u> instance in this example. But what if we had more methods? Or more objects? Or more threads?</p>
<p>Now, let&#8217;s make <strong>MyIncrement</strong> singleton:</p>
<pre class="brush: java;">
package ro.teo.singletonexample;

public class MyIncrement {
  private static class MyIncrementHolder{
    private final static MyIncrement
              INSTANCE=new MyIncrement();
  }

  public static MyIncrement getInstance(){
    return MyIncrementHolder.INSTANCE;
  }

  private int i;
  private MyIncrement(){
    i=0;
  }
  public int nextVal(){
    i++;
    return i;
  }
}
</pre>
<pre class="brush: java;">
package ro.teo.singletonexample;

public class SEMain {
  public static void main(String[] args){
    MyIncrement mi1=MyIncrement.getInstance();
    MyIncrement mi2=MyIncrement.getInstance();

    SomeInc si1=new SomeInc();
    SomeInc si2=new SomeInc();

    for (int i=0;i&amp;#60;10;i++){
      mi1.nextVal();
    }
    for (int i=0;i&amp;#60;4;i++){
      mi2.nextVal();
    }

    si1.doStuff(mi1);
    si2.doStuff(mi2);
  }
}
</pre>
<p>Let&#8217;s see the output in this case:</p>
<pre style="font-size:9pt;border:1px black solid;background-color:#EEEEEE;padding:3px;">
I do some serious stuff ...
15
I do some serious stuff ...
16
</pre>
<p>As you can see the sollution of <a href="http://en.wikipedia.org/wiki/Singleton_pattern#The_solution_of_Bill_Pugh">Bill Pugh</a> works fine.</p>
<p>We are going to use the pattern for the <strong>NewUrlsQueue</strong> for our focused web spider.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Singleton pattern in PHP 5]]></title>
<link>http://drenganathan.wordpress.com/2009/02/06/singleton-pattern-in-php-5/</link>
<pubDate>Fri, 06 Feb 2009 07:13:48 +0000</pubDate>
<dc:creator>Renga</dc:creator>
<guid>http://drenganathan.wordpress.com/2009/02/06/singleton-pattern-in-php-5/</guid>
<description><![CDATA[Singleton pattern In software engineering, the singleton pattern is a design pattern that is used to]]></description>
<content:encoded><![CDATA[Singleton pattern In software engineering, the singleton pattern is a design pattern that is used to]]></content:encoded>
</item>
<item>
<title><![CDATA[DESIGN PATTERNS in PHP]]></title>
<link>http://afruj.wordpress.com/2008/08/31/design-patterns-in-php/</link>
<pubDate>Sun, 31 Aug 2008 08:12:08 +0000</pubDate>
<dc:creator>afruj</dc:creator>
<guid>http://afruj.wordpress.com/2008/08/31/design-patterns-in-php/</guid>
<description><![CDATA[In software engineering, a design pattern is a general reusable solution to a commonly occurring pro]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>In <a title="Software engineering" href="http://en.wikipedia.org/wiki/Software_engineering">software engineering</a>, a <strong class="selflink">design pattern</strong> is a general reusable solution to a commonly occurring problem in <a title="Software design" href="http://en.wikipedia.org/wiki/Software_design">software design</a>. The advantage of knowing and using these patterns is save time as well as give developers a common language in software design. Here I discuss the implementation of some common design patterns that are easily adapted to PHP.</p>
<p><strong>1. Strategy Pattern:</strong></p>
<p>The strategy pattern is typically used when your programmer’s algorithm<br />
should be interchangeable with different variations of the algorithm. For<br />
example, if you have code that creates an image, under certain circumstances, you might want to create JPEGs and under other circumstances, you might want to create GIF files.<br />
The strategy pattern is usually implemented by declaring an abstract<br />
base class with an algorithm method, which is then implemented by inheriting concrete classes. At some point in the code, it is decided what concrete strategy is relevant; it would then be instantiated and used wherever relevant.<br />
Our example shows how a download server can use a different file selection<br />
strategy according to the web client accessing it. When creating the<br />
HTML with the download links, it will create download links to either .tar.gz<br />
files or .zip files according to the browser’s OS identification. Of course, this<br />
means that files need to be available in both formats on the server. For simplicity’s sake, assume that if the word “Win” exists in $_SERVER["HTTP_<br />
USER_AGENT"], we are dealing with a Windows system and want to create .zip<br />
links; otherwise, we are dealing with systems that prefer .tar.gz.<br />
In this example, we would have two strategies: the .tar.gz strategy and<br />
the .zip strategy, which is reflected as the following strategy hierarchy (see<br />
Figure 1).</p>
<p style="text-align:center;"><a href="http://afruj.files.wordpress.com/2008/08/sp.gif"><img class="aligncenter size-full wp-image-577" src="http://afruj.wordpress.com/files/2008/08/sp.gif" alt="" width="422" height="227" /></a><br />
Figure 1: Strategy hierarchy.</p>
<p style="text-align:left;">The following code snippet should give you an idea of how to use such a<br />
strategy pattern:<br />
abstract class FileNamingStrategy {<br />
abstract function createLinkName($filename);<br />
}<br />
class ZipFileNamingStrategy extends FileNamingStrategy {<br />
function createLinkName($filename)<br />
{<br />
return &#8220;http://downloads.foo.bar/$filename.zip&#8221;;<br />
}<br />
}<br />
class TarGzFileNamingStrategy extends FileNamingStrategy {<br />
function createLinkName($filename)<br />
{<br />
return &#8220;http://downloads.foo.bar/$filename.tar.gz&#8221;;<br />
}<br />
}<br />
if (strstr($_SERVER["HTTP_USER_AGENT"], &#8220;Win&#8221;)) {<br />
$fileNamingObj = new ZipFileNamingStrategy();<br />
} else {<br />
$fileNamingObj = new TarGzFileNamingStrategy();<br />
}<br />
$calc_filename = $fileNamingObj-&#62;createLinkName(&#8220;Calc101&#8243;);<br />
$stat_filename = $fileNamingObj-&#62;createLinkName(&#8220;Stat2000&#8243;);<br />
print &#60;&#60;&#60;EOF<br />
&#60;h1&#62;The following is a list of great downloads&#60;&#60;/h1&#62;<br />
&#60;br&#62;<br />
&#60;a href=&#8221;$calc_filename&#8221;&#62;A great calculator&#60;/a&#62;&#60;br&#62;<br />
&#60;a href=&#8221;$stat_filename&#8221;&#62;The best statistics application&#60;/a&#62;&#60;br&#62;<br />
&#60;br&#62;<br />
EOF;<br />
Accessing this script from a Windows system gives you the following<br />
HTML output:<br />
&#60;h1&#62;The following is a list of great downloads&#60;&#60;/h1&#62;<br />
&#60;br&#62;<br />
&#60;a href=&#8221;http://downloads.foo.bar/Calc101.zip&#8221;&#62;A great calculator&#60;<br />
/a&#62;&#60;br&#62;<br />
&#60;a href=&#8221;http://downloads.foo.bar/Stat2000.zip&#8221;&#62;The best statistics<br />
application&#60;/a&#62;&#60;br&#62;<br />
&#60;br&#62;</p>
<p style="text-align:left;">Tip: The strategy pattern is often used with the factory pattern, which is<br />
described later in this section. The factory pattern selects the correct strategy.</p>
<p style="text-align:left;"><strong>2. Singleton Pattern:</strong><br />
The singleton pattern is probably one of the best-known design patterns.<br />
You have probably encountered many situations where you have an object that<br />
handles some centralized operation in your application, such as a logger<br />
object. In such cases, it is usually preferred for only one such application-wide<br />
instance to exist and for all application code to have the ability to access it.<br />
Specifically, in a logger object, you would want every place in the application<br />
that wants to print something to the log to have access to it, and let the centralized<br />
logging mechanism handle the filtering of log messages according to<br />
log level settings. For this kind of situation, the singleton pattern exists.<br />
Making your class a singleton class is usually done by implementing a<br />
static class method getInstance(), which returns the only single instance of<br />
the class. The first time you call this method, it creates an instance, saves it in<br />
a private static variable, and returns you the instance. The subsequent<br />
times, it just returns you a handle to the already created instance.<br />
Here’s an example:<br />
class Logger {<br />
static function getInstance()<br />
{<br />
if (self::$instance == NULL) {<br />
self::$instance = new Logger();<br />
}<br />
return self::$instance;<br />
}<br />
private function __construct()<br />
{<br />
}<br />
private function __clone()<br />
{<br />
}<br />
function Log($str)<br />
{<br />
// Take care of logging<br />
}<br />
static private $instance = NULL;<br />
}<br />
Logger::getInstance()-&#62;Log(&#8220;Checkpoint&#8221;);</p>
<p style="text-align:left;">The essence of this pattern is Logger::getInstance(), which gives you<br />
access to the logging object from anywhere in your application, whether it is<br />
from a function, a method, or the global scope.<br />
In this example, the constructor and clone methods are defined as private.<br />
This is done so that a developer can’t mistakenly create a second<br />
instance of the Logger class using the new or clone operators; therefore, getInstance() is the only way to access the singleton class instance.</p>
<p style="text-align:left;"><strong>3. Factory Pattern:</strong></p>
<p style="text-align:left;">Polymorphism and the use of base class is really the center of OOP. However,<br />
at some stage, a concrete instance of the base class’s subclasses must be created.<br />
This is usually done using the factory pattern. A Factory class has a<br />
static method that receives some input and, according to that input, it decides<br />
what class instance to create (usually a subclass).<br />
Say that on your web site, different kinds of users can log in. Some are<br />
guests, some are regular customers, and others are administrators. In a common<br />
scenario, you would have a base class User and have three subclasses:<br />
GuestUser, CustomerUser, and AdminUser. Likely User and its subclasses would<br />
contain methods to retrieve information about the user (for example, permissions<br />
on what they can access on the web site and their personal preferences).<br />
The best way for you to write your web application is to use the base class<br />
User as much as possible, so that the code would be generic and that it would<br />
be easy to add additional kinds of users when the need arises.<br />
The following example shows a possible implementation for the four User<br />
classes, and the UserFactory class that is used to create the correct user object<br />
according to the username:<br />
abstract class User {<br />
function __construct($name)<br />
{<br />
$this-&#62;name = $name;<br />
}<br />
function getName()<br />
{<br />
return $this-&#62;name;<br />
}<br />
// Permission methods<br />
function hasReadPermission()<br />
{<br />
return true;<br />
}<br />
function hasModifyPermission()<br />
{<br />
return false;</p>
<p style="text-align:left;">}<br />
function hasDeletePermission()<br />
{<br />
return false;<br />
}<br />
// Customization methods<br />
function wantsFlashInterface()<br />
{<br />
return true;<br />
}<br />
protected $name = NULL;<br />
}<br />
class GuestUser extends User {<br />
}<br />
class CustomerUser extends User {<br />
function hasModifyPermission()<br />
{<br />
return true;<br />
}<br />
}<br />
class AdminUser extends User {<br />
function hasModifyPermission()<br />
{<br />
return true;<br />
}<br />
function hasDeletePermission()<br />
{<br />
return true;<br />
}<br />
function wantsFlashInterface()<br />
{<br />
return false;<br />
}<br />
}<br />
class UserFactory {<br />
private static $users = array(&#8220;Andi&#8221;=&#62;&#8221;admin&#8221;, &#8220;Stig&#8221;=&#62;&#8221;guest&#8221;,<br />
&#8220;Derick&#8221;=&#62;&#8221;customer&#8221;);<br />
static function Create($name)<br />
{<br />
if (!isset(self::$users[$name])) {<br />
// Error out because the user doesn&#8217;t exist<br />
}<br />
switch (self::$users[$name]) {</p>
<p style="text-align:left;">case &#8220;guest&#8221;: return new GuestUser($name);<br />
case &#8220;customer&#8221;: return new CustomerUser($name);<br />
case &#8220;admin&#8221;: return new AdminUser($name);<br />
default: // Error out because the user kind doesn&#8217;t exist<br />
}<br />
}<br />
}<br />
function boolToStr($b)<br />
{<br />
if ($b == true) {<br />
return &#8220;Yes\n&#8221;;<br />
} else {<br />
return &#8220;No\n&#8221;;<br />
}<br />
}<br />
function displayPermissions(User $obj)<br />
{<br />
print $obj-&#62;getName() . &#8220;&#8217;s permissions:\n&#8221;;<br />
print &#8220;Read: &#8221; . boolToStr($obj-&#62;hasReadPermission());<br />
print &#8220;Modify: &#8221; . boolToStr($obj-&#62;hasModifyPermission());<br />
print &#8220;Delete: &#8221; . boolToStr($obj-&#62;hasDeletePermission());<br />
}<br />
function displayRequirements(User $obj)<br />
{<br />
if ($obj-&#62;wantsFlashInterface()) {<br />
print $obj-&#62;getName() . &#8221; requires Flash\n&#8221;;<br />
}<br />
}<br />
$logins = array(&#8220;Andi&#8221;, &#8220;Stig&#8221;, &#8220;Derick&#8221;);<br />
foreach($logins as $login) {<br />
displayPermissions(UserFactory::Create($login));<br />
displayRequirements(UserFactory::Create($login));<br />
}<br />
<strong>Running this code outputs</strong><br />
Andi&#8217;s permissions:<br />
Read: Yes<br />
Modify: Yes<br />
Delete: Yes<br />
Stig&#8217;s permissions:<br />
Read: Yes<br />
Modify: No<br />
Delete: No<br />
Stig requires Flash<br />
Derick&#8217;s permissions:<br />
Read: Yes<br />
Modify: Yes<br />
Delete: No<br />
Derick requires Flash<br />
This code snippet is a classic example of a factory pattern. You have a class<br />
hierarchy (in this case, the User hierarchy), which your code such as displayPermissions() treats identically. The only place where treatment of the classes differ is in the factory itself, which constructs these instances. In this example, the factory checks what kind of user the username belongs to and creates its class accordingly. In real life, instead of saving the user to user-kind mapping in a static array, you would probably save it in a database or a configuration file.</p>
<p style="text-align:left;"><strong>Tip:</strong> Besides Create(), you will often find other names used for the factory<br />
method, such as factory(), factoryMethod(), or createInstance().</p>
<p style="text-align:left;"><strong>4. Observer Pattern:</strong></p>
<p style="text-align:left;">PHP applications, usually manipulate data. In many cases, changes to one<br />
piece of data can affect many different parts of your application’s code. For<br />
example, the price of each product item displayed on an e-commerce site in the<br />
customer’s local currency is affected by the current exchange rate. Now,<br />
assume that each product item is represented by a PHP object that most likely<br />
originates from a database; the exchange rate itself is most probably being<br />
taken from a different source and is not part of the item’s database entry. Let’s<br />
also assume that each such object has a display() method that outputs the<br />
HTML relevant to this product.<br />
The observer pattern allows for objects to register on certain events<br />
and/or data, and when such an event or change in data occurs, it is automatically<br />
notified. In this way, you could develop the product item to be an observer<br />
on the currency exchange rate, and before printing out the list of items, you<br />
could trigger an event that updates all the registered objects with the correct<br />
rate. Doing so gives the objects a chance to update themselves and take the<br />
new data into account in their display() method.<br />
Usually, the observer pattern is implemented using an interface called<br />
Observer, which the class that is interested in acting as an observer must<br />
implement.<br />
For example:</p>
<p style="text-align:left;">interface Observer {<br />
function notify($obj);<br />
}<br />
An object that wants to be “observable” usually has a register method<br />
that allows the Observer object to register itself. For example, the following<br />
might be our exchange rate class:</p>
<p style="text-align:left;">class ExchangeRate {<br />
static private $instance = NULL;<br />
private $observers = array();<br />
private $exchange_rate;<br />
private function ExchangeRate() {<br />
}<br />
static public function getInstance() {<br />
if (self::$instance == NULL) {<br />
self::$instance = new ExchangeRate();<br />
}<br />
return self::$instance;<br />
}<br />
public function getExchangeRate() {<br />
return $this-&#62;$exchange_rate;<br />
}<br />
public function setExchangeRate($new_rate) {<br />
$this-&#62;$exchange_rate = $new_rate;<br />
$this-&#62;notifyObservers();<br />
}<br />
public function registerObserver($obj) {<br />
$this-&#62;observers[] = $obj;<br />
}<br />
function notifyObservers() {<br />
foreach($this-&#62;observers as $obj) {<br />
$obj-&#62;notify($this);<br />
}<br />
}<br />
}<br />
class ProductItem implements Observer {<br />
public function __construct() {<br />
ExchangeRate::getInstance()-&#62;registerObserver($this);<br />
}<br />
public function notify($obj) {<br />
if ($obj instanceof ExchangeRate) {<br />
// Update exchange rate data<br />
print &#8220;Received update!\n&#8221;;<br />
}<br />
}<br />
}<br />
$product1 = new ProductItem();<br />
$product2 = new ProductItem();<br />
ExchangeRate::getInstance()-&#62;setExchangeRate(4.5);<br />
<strong>This code prints</strong><br />
Received update!<br />
Received update!</p>
<p style="text-align:left;">Although the example isn’t complete (the ProductItem class doesn’t do<br />
anything useful), when the last line executes (the setExchangeRate() method), both $product1 and $product2 are notified via their notify() methods with the new exchange rate value, allowing them to recalculate their cost.<br />
This pattern can be used in many cases; specifically in web development,<br />
it can be used to create an infrastructure of objects representing data that<br />
might be affected by cookies, GET, POST, and other input variables.</p>
<p style="text-align:left;">Thanks to the advances of PHP 5, using common OO methodologies, such as<br />
design patterns, has now become more of a reality than with past PHP versions. For more you can visit http://www.cetus-links.org/.</p>
<p style="text-align:left;">
<p style="text-align:left;">
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[static classes statt singleton]]></title>
<link>http://susanneurich.wordpress.com/2008/08/01/static-classes-statt-singleton/</link>
<pubDate>Fri, 01 Aug 2008 18:08:38 +0000</pubDate>
<dc:creator>Susann</dc:creator>
<guid>http://susanneurich.wordpress.com/2008/08/01/static-classes-statt-singleton/</guid>
<description><![CDATA[Unter bestimmten Umständen, kann ab c# 2.0 statt des singleton patterns eine &#8220;static class]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Unter bestimmten Umständen, kann ab c# 2.0 statt des <a href="http://susanneurich.wordpress.com/2007/09/27/singleton-pattern/" target="_self">singleton patterns</a> eine &#8220;<a href="http://msdn.microsoft.com/de-de/library/79b3xss3.aspx" target="_blank">static class</a>&#8221; verwendet werden</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Singleton Pattern]]></title>
<link>http://susanneurich.wordpress.com/2007/09/27/singleton-pattern/</link>
<pubDate>Thu, 27 Sep 2007 19:58:13 +0000</pubDate>
<dc:creator>Susann</dc:creator>
<guid>http://susanneurich.wordpress.com/2007/09/27/singleton-pattern/</guid>
<description><![CDATA[Definition: &#8220;The Singleton Pattern ensures a class has only one instance, and provides a globa]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Definition:<br />
&#8220;The <strong>Singleton</strong> Pattern ensures a class has only one instance, and provides a global point of access to it.&#8221;</p>
<p>Anmerkungen dazu:</p>
<p>Das Beispiel im Head First ist der Boiler in der Schokoladenfabrik.</p>
<p>Ein interessanter Artikel zur richtigen Verwendung vom Singleton gibt bei <a target="_blank" href="http://steve.yegge.googlepages.com/singleton-considered-stupid">Steve Yegge</a> zu lesen</p>
</div>]]></content:encoded>
</item>

</channel>
</rss>
