Singleton Design Pattern的优势是什么?

Tho*_*mas 7 c# oop

例如,每个人都知道如何为Singleton Design Pattern.say编写代码

public class Singleton  
{  
    // Private static object can access only inside the Emp class.  
    private static Singleton instance;  

    // Private empty constructor to restrict end use to deny creating the object.  
    private Singleton()  
    {  
    }  

    // A public property to access outside of the class to create an object.  
    public static Singleton Instance  
    {  
        get  
        {  
            if (instance == null)  
            {  
                instance = new Singleton();  
            }  
            return instance;  
        }  
    }  
}  
Run Code Online (Sandbox Code Playgroud)

很明显,当我们创建任何类的实例时,很多时候会为每个实例分配内存,但在Singleton设计模式的情况下,单个实例为所有调用提供服务.

1)我有点困惑,真的没有意识到原因是什么......当一个人应该选择Singleton Design Pattern时.只是为了节省一些记忆或任何其他好处.

2)假设任何单个程序可以有多个类,那么哪些类应遵循Singleton设计模式?Singleton Design Pattern的优势是什么?

3.在现实生活中的应用程序何时应该按照Singleton Design Pattern进行任何课程?谢谢

这是线程安全的单例

public sealed class MultiThreadSingleton   
{   
    private static volatile MultiThreadSingleton instance;   
    private static object syncRoot = new Object();   

    private MultiThreadSingleton()   
    {   
    }   

    public static MultiThreadSingleton Instance   
    {   
        get   
        {   
            if (instance == null)   
            {   
                lock (syncRoot)   
                {   
                    if (instance == null)   
                    {   
                        instance = new MultiThreadSingleton();   
                    }   
                }   
            } 

        return instance;   
        }   
    }   
}
Run Code Online (Sandbox Code Playgroud)

sgu*_*gud 8

每次只确保对象的一个​​相同实例.

举一个场景,比如公司申请,只有一个CEO.如果要创建或访问CEO对象,则每次都应返回相同的CEO对象.

另外,在登录应用程序后,当前用户每次都必须返回相同的对象.


ozg*_*gur 8

其他答案也很好。但他们提供了模式行为特征的示例。但是,单例更多的是关于创造。因此,该模式最重要的好处之一是它是资源友好的。new object当您实际上不需要新内存时,您不会浪费内存。

这带来了另一个好处,即避免了实例化开销。