(三十二)单例设计模式

/**
设计模式:解决某一类问题最有效的方式(23种设计模式)
单例设计模式:保证一个类只有一个对象
1.构造函数私有化,禁止外部使用实例化new
2.再类内部创建一个自身类型的对象
3.使用一个public的函数将该对象返回
*/
class Demo14
{
    public static void main(String[] args)
    {
        //Single s1 = new Single();
        //Single s2 = new Single();
        Single s1 = Single.getInstance();
        Single s2 = Single.getInstance();
        System.out.println(s1==s2);//true实现了一个类只有一个对象
    }
}
//饿汉式(推荐使用)
class Single
{
    private Single() {}
    private static Single s = new Single();//无论getInstance方法会不会被调用,该对象都会创建
    public static Single getInstance()
    {
        return s;
    }
}
//懒汉式(多线程使用有问题)
class Single2
{
    private static Single2 s;
    private Single2() {}
    public static Single2 getInstance()
    {
        if(s==null)
            s = new Single2();
        return s;
    }
}

  

单例设计模式的使用 
/**
这是单例设计模式的简单使用,实现工厂的零件的加功,不同车间加载一批零件
@author czy
@version 1.0
*/
class Demo15
{
    public static void main(String[] args)
    {
        Factory f1 = Factory.getInstance();
        for(int i = 0;i<5;i++) {
        f1.JiaGong();//1,2,3,4,5
        }
        Factory f2 = Factory.getInstance();
        f2.JiaGong();//6
        f2.JiaGong();//7
    }
}
class Factory
{
    private Factory() {}
    private int num;
    private static Factory f = new Factory();
    public static Factory getInstance()
    {
        return f;
    }
    public void JiaGong()
    {
        System.out.println("这是加工的第" + ++num + "个零件");
    }
 
}
 
单例模式的使用二:
class Demo16
{
    public static void main(String[] args)
    {
        SuperMan sm1 = SuperMan.getInstance();
        System.out.println(sm1.getName());
    }
}
class SuperMan
{
    private String name;
    private SuperMan() {}
    private SuperMan(String name)
    {
        this.name = name;
    }
    private static SuperMan sm = new SuperMan("克拉克");
    public static SuperMan getInstance()
    {
        return sm;
    }
    public String getName()
    {
        return name;
    }
 
}
 
 
原文地址:https://www.cnblogs.com/bgwhite/p/9377781.html