单例模式

来源:互联网 发布:windows 探测udp 端口 编辑:程序博客网 时间:2024/05/17 22:37


//饿汉试

public class Singleton {

    //1.将构造方法私有化,不允许外部直接创建对象
    private Singleton(){        
    }
    
    //2.创建类的唯一实例,使用private static修饰
    private static Singleton instance=new Singleton();
    
    //3.提供一个用于获取实例的方法,使用public static修饰
    public static Singleton getInstance(){
        return instance;
    }
}



//懒汉式

public class Singleton2 {
    //1.将构造方式私有化,不允许外边直接创建对象
    private Singleton2(){
    }
    
    //2.声明类的唯一实例,使用private static修饰
    private static Singleton2 instance;
    
    //3.提供一个用于获取实例的方法,使用public static修饰
    public static Singleton2 getInstance(){
        if(instance==null){
            instance=new Singleton2();
        }
        return instance;
    }
}



//测试类

public class Test {
    public static void main(String[] args) {
        //饿汉模式
        Singleton s1=Singleton.getInstance();
        Singleton s2=Singleton.getInstance();
        if(s1==s2){
            System.out.println("s1和s2是同一个实例");
        }else{
            System.out.println("s1和s2不是同一个实例");
        }
        
        //懒汉模式
        Singleton2 s3=Singleton2.getInstance();
        Singleton2 s4=Singleton2.getInstance();
        if(s3==s4){
            System.out.println("s3和s4是同一个实例");
        }else{
            System.out.println("S3和s4不是同一个实例");
        }
        
    }
}




0 0
原创粉丝点击