单例模式(构造方法私有化)

单例模式就是只创建一个实例化对象。

单例模式分为两种,饿汉式和懒汉式,饿汉式是不管你用不用,我先给你实例化一个对象代码如下

class Singleton{
    String name="阿臀";
    private static Singleton action=new Singleton();  //先实例化一个对象,并且将其私有化     
    public static Singleton getaction() {   //提供一个可以访问返回值为对象的方法
        return action;
    }
}
public class WWW {

    public static void main(String[] args) {
        Singleton a1=Singleton.getaction();  //实例化对象
        Singleton a2=Singleton.getaction(); //实例化对象
        Singleton a3=Singleton.getaction();  //实例化对象
        System.out.println(a1);  //输出对象的地址
        System.out.println(a2);  //输出对象的地址
        System.out.println(a3);  //输出对象的地址
        System.out.println(a2.name);
    }
}

此为输出,三个实例化的对象地址相同。

posted on 2018-01-09 09:34  acaca  阅读(1579)  评论(0编辑  收藏  举报