Vote Up 0 Vote Down

singleton design pattern

How many different way singleton can be achieved?

edited on 15/8/16

answers


Vote Up 0 Vote Down

An implementation of the singleton pattern must:

ensure that only one instance of the singleton class ever exists; and provide global access to that instance. Typically, this is achieved by:

declaring all constructors of the class to be private; and providing a static method that returns a reference to the instance. The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called. The following is a sample implementation written in Java.

public final class Singleton { private static final Singleton instance = new Singleton(); private Singleton() {}

public static Singleton getInstance() {
    return instance;
}

} Lazy initialization[edit] A singleton implementation may use lazy initialization, where the instance is created when the static method is first invoked. If the static method may be called from multiple threads simultaneously, measures must be taken to prevent race conditions that might result in the creation of multiple instances of the class. The following is a thread-safe sample implementation, using lazy initialization, written in Java.

public final class Singleton { private static Singleton instance = null; private Singleton() {}

public static synchronized Singleton getInstance() {
    if (instance == null) instance = new Singleton();
    return instance;
}

}

WikiPedia

Singleton

flag | link
Vote Up 0 Vote Down

this was great to explore script also work for anyone who like to explore thing quicky but im afraid to said that we need to me more flexible if we need to achive assignment assistance anything good in our life

flag | link

your answer

Who Are You?

Have an account already? Login before answering!