Holla,
In Bokels Blog Archiv habe ich das gefunden....
http://www.helpqlodhelp.com/blog/archives/2003_09.html
AS7: Executing once
Geht darum, wie man Instanzen erzeugen kann wenn die Klasse deklariert wird. Diese Technik kann man wunderbar mit dem Singleton Pattern verbinden.
Beim Singleton Pattern gibt es nur eine Instanz - also kann man diese Instanz auch zur Deklarationszeit erzeugen.
Aus Gof Intent für ein Singleton:
"Ensure a class only has one instance, and provide a global point of access to it"
Prima Beispiel ist eine Klasse, die Konfigurationen einer Applikation speichert.
Die Klasse unten benutzt dafür einen Hashtable.
http://java.sun.com/j2se/1.3/docs/ap...Hashtable.html
Singleton ist super praktisch aus vielen Gründen... vorallem aber der globale
Einsprungspunkt.
Wers nicht kennt - unbedingt anschauen
Viele Grüße, Nico.
PHP-Code:
/**
* Preferences Singleton
* Keeper of the Preferences within a project
* <code>
* var prefs : Preferences = Preferences.getInstance();
* prefs.setPropery ("language", "DE");
* prefs.setPropery ("someInt", 5);
* [...]
* //somewhere in your project...
* var lang = Preferences.getInstance().getPropery("language");
* </code>
*/
import somePackage.HashTable;
import somePackage.Enumeration;
class Preferences {
private var props : HashTable;
//create instance when class is declared
private static var instance = new Preferences();
/**
* get the Preferences Instance
* @return instance of Preferences
*/
public static getInstance() : Preferences {
return instance;
};
/**
* private constructor
* get instance by getInstance
*/
private function Preferences() {
props = new HashTable();
};
/**
* set a Propery
* @param name of the property
* @param value of the propery, no special type
* @return null if prop wasn't set before, oldvalue if prop was set before
*/
public function setProperty (name : String, value) {
return props.put (name, value);
};
/**
* get a property
* @param name of the propery
* @return value of the propery or null
*/
public function getProperty (name : String) {
return props.get(name);
};
/**
* check existance of a property
* @param name of the propery
* @return boolean property exists
*/
public function hasProperty (name : String) : Boolean {
return props.containsKey(name);
};
/**
* @return names of all props as Enumeration
*/
public function getPropertyKeys() : Enumeration {
return props.keys();
};
};