设计模式-单例模式

1.用到的类

一个用于获取单例的类。

2.实现代码

懒汉式

/**
 * 懒汉式单例模式
 */
public class SingleLazy {
    private static SingleLazy singleLazy = new SingleLazy();

    public static SingleLazy getInstance()
    {
        return singleLazy;
    }
}

饿汉式

/**
 * 饿汉式单例
 *
 */
public class HungrySingle {
    private static HungrySingle instance = null;

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

你可能感兴趣的:(设计模式,单例模式)