开发者

What are singletons?? how to use them?? and why to use them? [duplicate]

开发者 https://www.devze.com 2023-02-06 10:38 出处:网络
This question already has answers here: Closed 12 years ag开发者_Go百科o. Possible Duplicate: Singleton: How should it be used
This question already has answers here: Closed 12 years ag开发者_Go百科o.

Possible Duplicate:

Singleton: How should it be used

hello. i want to know what a singleton is? how to use it? and why do i have to use it. thank you very much. if anybody can give examples with the explanation i would really appreciate it.


If you need only a single instance of an object, then you use singleton. It is one of the many standard design patterns.

Let me clarify with a piece of code -

public class SingleInstance
{
    private static final SingleInstance OnlyInstance = new SingleInstance();   // Or Any other value

    // Private constructor, so instance cannot be created outside this class
    private SingleInstance(){};

    public static getSingleInstance()
    {
        return OnlyInstance;
    }
}

Since this class's constructor is private, it cannot be instantiated in your application, thus ensuring that you have exactly one instance of class SingleInstance.

Use this pattern when you need to ensure only one instance of a particular class is created within your entire application.

To learn more, go here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号