الاثنين، 15 ديسمبر 2008

Singleton Pattern

Singleton Pattern

Role

Classfied as a Creational Pattern

The purpose of the Singleton pattern is to ensure that there is only one instance of a class, and that there is a global access point to that object. The pattern ensures that the class is instantiated only once and that all requests are directed to that one and only object. Moreover, the object should not be created until it is actually needed. In the Singleton pattern, it is the class itself that is responsible for ensuring this constraint, not the clients of the class.

 

Design

The Singleton pattern adds functionality by modifying an existing class. The modifications required are:

·         Make the constructor private and add a private static constructor as well.

·         Add a private static read-only object that is internally instantiated using the private constructor.

·         Add a public static property that accesses the private object.

 UML Digram 


The visible players in the Singleton pattern are:

Singleton

The class containing the mechanism for a unique instance of itself

Instance

A property for making and accessing an instance of the Singleton class

 Example

class SingletonCreator

        {

            private SingletonCreator()

            {

            }

            static int flag = 0;

            private static SingletonCreator uniqueInstance =

                                       new SingletonCreator();

            public static SingletonCreator UniqueOnlyOneInstance()

            {

                if (flag==0)

                {

                    flag = 1;

                    return uniqueInstance;   

                }

                else

                {

                    return null;

                }

            }

 call it in Main 

SingletonCreator unique = SingletonCreator.UniqueOnlyOneInstance();

0 التعليقات: