// Singleton
// Intent: "Ensure a class only" one INE Instance, And Provide a Global
// Point of access to it.
// for Further Information, Read "Design Patterns", P127, Gamma et al.,
// addison-wesley, ISBN: 0-201-63361-2
/ * Notes:
* If it makessese to have.com (a so-caled
* Singleton, Then It Makes Sense To Enforce this (To Elimintate Potential
* Errors, ETC).
*
* A class based on the Singleton Design Pattern Protects ITS Construction,
* SO That Only The Class Itself (E.g. in a static method) May Instantiate Itself.
* IT Exposes An Instance Method Which Allows Client Code to Retrieve To
* Current Instance, And if it does not exist to instantiate it.
* /
Namespace Singleton_DesignPattern
{
Using system;
Class Singleton
{
Private static singleton _INSTANCE
Public Static Singleton Instance ()
{
IF (_Instance == null)
_INSTANCE = New Singleton ();
Return_INSTANCE;
}
protected singleton () {}
// Just to Prove Only A Single Instance EXISTS
PRIVATE INT x = 0;
Public void setx (int newval) {x = newval;
Public int getX () {return x;}
}
///
/// Summary Description for Client.
/// summary>
Public Class Client
{
Public Static Int
Main
(String [] ARGS)
{
Int Val;
// can't Call New, Because Constructionor is protected
Singleton firstsingleton = singleton.instance ();
Singleton Secondsingleton = Singleton.instance ();
// Now we have two variables, butboth shouth stay refer to the Same Object
// let's prot this, by setting a value using one variable, and
// (Hopefully!) Retrieving The Same Value Using The Second Variable
Firstsingleton.setX (4);
Console.writeline ("Using First Variable for Singleton, Set X To 4"); VAL = Secondsingleton.getx ();
Console.writeline ("Using Second Variable for Singleton, Value Retrieved = {0}", VAL);
Return 0;
}
}
}