定义一个单例设计Singleton


class Singleton{
    private static Singleton instance;//内部实例化对象
    public static Singleton getInstance(){
        if(instance == null){
            instance =  new Singleton();
        }
        return instance;
    }
    private Singleton(){} //构造方法私有化
    public void print(){
        System.out.println("hellow word");
    }
     
    
}

public class Lxd{
    public static void main(String[] args) {
        Singleton s = null; //声明对象
        s = Singleton.getInstance(); //直接访问Static属性
        s.print(); //使用方法
    }
}

 

class Singleton{
    private static final Singleton instance = new Singleton();//内部实例化对象
    public static Singleton getInstance(){  //调用实例对象的方法
        return instance;
    }
    private Singleton(){} //构造方法私有化
    public void print(){
        System.out.print("hello");
    }
}

public class LxdT {
    public static void main(String[] args) {
        Singleton s = Singleton.getInstance();  //类名.方法名调用
        s.print();  //使用方法
    
    }
    
}

 

posted @ 2017-12-04 22:02  沃泽法克  阅读(287)  评论(0编辑  收藏  举报