java怎么使用静态关键字实现单例模式

这篇文章主要介绍java怎么使用静态关键字实现单例模式,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

单例模式:只能获得某个类的唯一一个实例

单例模式,不管什么时间点得到的对象都是同一个对象

看下面代码:

/**
 * 单例模式
 * @author xiongda
 * @date 2018年4月15日
 */
public class SingletonMode {
  private static SingletonMode single =null;
  public int number = 1;
  
  //将构造方法定义为私有
  private SingletonMode(){
    single=this;
  }
  public static SingletonMode getInstance(){
    if(single==null){
      single=new SingletonMode();
    }
    return single;
  }
}

将构造方法私有,以便实现外部无法使用new进行实例化的效果,达到任何时候其实都是同一个对象的效果

测试代码如下:

public class Testit {

public static void main(String[] args) {
// TODO Auto-generated method stub
SingletonMode single =SingletonMode.getInstance();
System.out.println("single的number值:"+single.number);

SingletonMode single2 =SingletonMode.getInstance();
single2.number=100;

SingletonMode single3 =SingletonMode.getInstance();
System.out.println("single3的number值:"+single3.number);

System.out.println(single2==single3);
}

}

结果如下:

java怎么使用静态关键字实现单例模式

该结果表明:single、single2、single3这些引用指向的都是同一个对象

单例模式的应用:比如游戏窗口,通过单例模式来控制不能多开

以上是“java怎么使用静态关键字实现单例模式”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!