现在的位置: 首页 > 综合 > 正文

单例模式-singleton

2017年12月03日 ⁄ 综合 ⁄ 共 577字 ⁄ 字号 评论关闭

package day08_static;

/**
*
* @author tarena
* 单例设计模式
* 保证实例唯一,节省内存,对象不会改变
* 只能new一次,把new写成一个方法,调用的时候只能调用这个方法
*
*/

public class Singleton {

    private static Singleton si;

   private Singleton() {}//私有构造

   public static Singleton getInstance() {
        if (si == null) {// 判断是否为null,如果为null,则new一次,确保只有一个对象
           si = new Singleton();
       }
        return si;
    }

}

 

/**
* 单例测试类
* @author hsy
*
*/

public class TestSingleton {

   public static void main(String[] args) {
       Singleton si1 = Singleton.getInstance();
       Singleton si2 = Singleton.getInstance();
        System.out.println(si1 == si2);
   }
}

 

运行结果输出为 true

说明单例模式中,singleton的对象只new 一次。

抱歉!评论已关闭.