单例

package 单例;
/*
* 单例(单态)设计模式:在某个app中只有一个对象被创建
* 1.构造方法私有,防止在类的外部通过new构造方法的方式创建
*   饿汉式  不会出现线程安全问题
* 1.构造私有
* 2.定义一个静态的私有的本类对象
* 3.提供一个静态方法返回本类对象
*
* */
public class A {
   static final A a =new A();  //在内部new一个静态
    private A(){  //私有构造方法 因为构造函数私有了,外界都不能使用,所以这个对象应该在这个类里面创建
        System.out.println("哈哈");
    }


    public static A getA(){  // 所以应该提供一个公开的get方法,供外界使用;
        return a;
    }
}
package 单例;

/*
 * 懒汉式单例  需要 synchronized 加锁 不然多线程要出错
 *  1.构造私有
 *  2.
 * */
public class A2 {
    private static A2 a;  //在内部new一个静态
    private A2() {  //私有构造方法 因为构造函数私有了,外界都不能使用,所以这个对象应该在这个类里面创建
        System.out.println("哈哈");
    }


    public static synchronized A2 getA() {  // 所以应该提供一个公开的get方法,供外界使用;
        if (a == null) { //不过为空new一次 不为空不new
            a = new A2();
        }
        return a;
    }
}
package 单例;

public class testA {
    public static void main(String[] args) {
        A a =A.getA();
        A b =A.getA();
        System.out.println(a==b);

        A2 a1 = A2.getA();
        A2 b1 = A2.getA();
        System.out.println(a1);
        System.out.println(b1);
        System.out.println(a1==b1);
    }
}
原文地址:https://www.cnblogs.com/houtian2333/p/10702851.html