Wednesday, March 10, 2010

SemanticBlog

all about web innovation

Design Patterns: Singleton

Posted by admin On Juli - 11 - 2009

Das Singleton ist ein in der Softwareentwicklung eingesetztes Entwurfsmuster und gehört zur Kategorie der Erzeugungsmuster (engl. Creational Patterns). Es verhindert, dass von einer Klasse mehr als ein Objekt erzeugt werden kann, und stellt einen globalen Zugriffspunkt auf eine Instanz bereit.
Das Muster ist eines der von der so genannten Viererbande (GoF) publizierten Muster.

Das Singleton findet Verwendung, wenn

  • nur ein Objekt zu einer Klasse existieren darf und ein einfacher Zugriff auf dieses Objekt benötigt wird oder
  • wenn das einzige Objekt durch Unterklassenbildung spezialisiert werden soll.

Das Singleton-Pattern

  • erzeugt und verwaltet das einzige Objekt der Klasse
  • bietet globalen Zugriff auf dieses Objekt über eine Instanzoperation (getInstance(); ).
  • die Instanzoperation ist eine Klassenmethode, das heißt statisch gebunden
  • das private Attribut „Instanz“ (instance) ist ein Klassenattribut, das heißt ein statisches Attribut

Vorteile:

  • Das Muster bietet eine Verbesserung gegenüber globalen Variablen.
  • Zugriffskontrolle kann realisiert werden.
  • Das Singletonkann durch Unterklassenbildung spezialisiert werden.
  • Welche Unterklassen verwendet werden soll, kann zur Laufzeit entschieden werden.
  • Sollten später mehrere Objekte benötigt werden, ist eine Änderung leicht(er) möglich.

Nachteile:
Es besteht die große Gefahr, durch übermäßige Verwendung von Singletons ein objektorientiertes Äquivalent zu globalen Variablen zu implementieren.

Java:

public final class Singleton {

/**
* Privates Klassenattribut,
* wird beim erstmaligen Gebrauch (nicht beim Laden) der Klasse erzeugt
*/
private static Singleton instance;

/** Konstruktor ist privat, darf nicht von außen instanziiert werden. */
private Singleton() {}

/**
* Statische Methode "getInstance()" liefert die einzige Instanz der Klasse zurück.
* Ist synchronisiert und somit thread-sicher.
*/
public synchronized static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

Eager Creation:
Implementierung mit Enum in Java ab Version 5
Ab Version 5 kann zur Implementierung des Singleton-Patterns das Sprachkonstrukt Enum genutzt werden, welches außerdem direkt die Serialisierbarkeit ermöglicht.

public enum Singleton {
INSTANCE;
}

C#: The simplest of all is:

public class Singleton
{
// The combination of static and readonly makes the instantiation
// thread safe.  Plus the constructor being protected (it can be
// private as well), makes the class sure to not have any other
// way to instantiate this class than using this member variable.

public static readonly Singleton Instance = new Singleton();

// Protected constructor is sufficient to avoid other instantiation
// This must be present otherwise the compiler provides a default
// public constructor
//
protected Singleton()
{
}
}

Dieses Beispiel ist thread-sicher und benutzt lazy initialization.
Siehe auch http://www.yoda.arachsys.com/csharp/beforefieldinit.html

/// Class implements singleton pattern.

public class Singleton
{
// Protected constructor is sufficient to avoid other instantiation
// This must be present otherwise the compiler provides
// a default public constructor
protected Singleton()
{
}

/// Return an instance of <see cref="Singleton"/>

public static Singleton Instance
{
get
{
/// An instance of Singleton wont be created until the very first
/// call to the sealed class. This is a CLR optimization that
/// provides a properly lazy-loading singleton.
return SingletonCreator.CreatorInstance;
}
}

/// Sealed class to avoid any heritage from this helper class

private sealed class SingletonCreator
{
// Retrieve a single instance of a Singleton
private static readonly Singleton _instance = new Singleton();

//explicit static constructor to disable beforefieldinit
static SingletonCreator() { }

/// Return an instance of the class <see cref="Singleton"/>

public static Singleton CreatorInstance
{
get { return _instance; }
}
}
}

Implementierung als Generic in C# ab .Net 2.0:

Mit dieser Implementierung muss das Singleton nur einmal implementiert werden. Auf seiner Basis können dann leicht mehrere verschiedene Singletons erzeugt werden:

public class Singleton<T>
where T : new()
{
public static readonly T Instance=new T();
}

Ein konkreter Singleton würde dann in etwa so aussehen:

class MeinSingleton : Singleton<MeinSingleton>
{
}

Der Zugriff erfolgt hier über:

MeinSingleton.Instance

PHP (ab Version 5):

<?php
class Singleton {

// Anlegen der Instanz
private static $instance = NULL;

//Konstruktor private, damit die Klasse nur aus sich selbst heraus instanziiert werden kann.
private function __construct() {}

// Diese statische Methode gibt die Instanz zurueck.
public static function getInstance() {

if (self::$instance === NULL) {
self::$instance = new self;
}
return self::$instance;
}
// Klonen per 'clone()' von außen verbieten.
private function __clone() {}
}

$singleton = Singleton::getInstance();
?>

Ein weiteres Beispiel (Zandstra, Matt(2008): PHP Objects,Patterns, and Practice second Edition, aPress, S.147):

<?php
class Preferences {
private $props = array ();
private static $instance;
private function __construct() {
}
public static function getInstance() {
if (empty ( self::$instance )) {
self::$instance = new Preferences ( );
}
return self::$instance;
}
public function setProperty($key, $val) {
$this->props [$key] = $val;
}
public function getProperty($key) {
return $this->props [$key];
}
}
?>

Ruby: Ruby kommt wohl mit dem kleinsten Quellcode aus:

require 'singleton'

class Example
include Singleton
end

Javascript:

var Singleton = (function() {
var instance = null;

function PrivateConstructor() {
var rand = Math.round(Math.random() * 100);
this.getRand = function() {
return rand;
}
}

return new function() {
this.getInstance = function() {
if (instance == null) {
instance = new PrivateConstructor();
instance.constructor = null;
}
return instance;
}
}
})();

var singletonInstance = Singleton.getInstance();

>

Quellen:



Related posts:

  1. Design Patterns: Überblick
  2. Design Patterns für Benutzerschnittstellen

blog comments powered by Disqus

Blogverzeichnis - Blog Verzeichnis bloggerei.de   Blogverzeichnis   Blog and ping   Blog Top Liste - by TopBlogs.de   Bloggeramt.de   Blog Directory   powered by rankingcloud   Internet Multimedia blogs & blog posts  
blog search directory   Blogverzeichnis   Blog Directory   Blog Verzeichnis   Blog Directory   Technology Blogs - Blog Rankings   blogoscoop  

Clicky