单例模式

来源:互联网 发布:制作蹭饭地图软件 编辑:程序博客网 时间:2024/05/26 22:09

      单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。

那么我们有两种解决方案

方案一:

class Singleton
{
    private static Singleton singleton = new Singleton();
    private Singleton()
    {
        
    }
    public static Singleton getInstance()
    {
    
        
        return singleton;
    }
}


方案二
class Singleton
{
    private static Singleton singleton = null;
    private Singleton()
    {
        
    }
    public static Singleton getInstance()
    {
        if(singleton == null)
        {
            singleton = new Singleton();
            return singleton;
        }
        
        return singleton;
    }
}




0 0