单例设计模式

单例设计模式

具体实现

(1)将构造方法私有化,使其不能在类的外部通过new关键字实例化该类对象。

(2)在该类内部产生一个唯一的实例化对象,并且将其封装为private static类型。

(3)定义一个静态方法返回这个唯一对象。

public class testStream {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    //该类只能有一个实例
    private testStream() {
    }

   //目的是为了将构造器限定为private 避免类在外部实例化
    //在同一个虚拟机范围内  单例出来的都是唯一实例 只能通过一个方向访问

    private static testStream ts1 = null;
  
    
    //这个类必须给整个系统提供这个实例对象
    public static testStream getTest() {
        if(ts1 == null) {
            ts1 = new testStream();
        }
        return ts1;
    }
}

 测试:

public class testMain {
    public static void main(String[] args) {
    
        //testStream s = new testStream();//构造器私有化 不能new出来
        testStream stream1 = testStream.getTest();
        
        stream1.setName("李楠");
        
        testStream stream2 = testStream.getTest();
        stream2.setName("余杰");
        
        System.out.println(stream1.getName() + "   " + stream2.getName());//输出:余杰   余杰
        
        if(stream1 == stream2) {
            System.out.println("相同的实例");//输出:相同的实例
        }
        else if(stream1 != stream2){
            System.out.println("no");
        }
    }
}

参考:

https://www.cnblogs.com/binaway/p/8889184.html

坚持学习,永远年轻,永远热泪盈眶
原文地址:https://www.cnblogs.com/jiang0123/p/11288522.html