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

2025-05-29 0 54

本文为大家分享了使用静态关键字实现单例模式的具体代码,供大家参考,具体内容如下

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

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

看下面代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20
/**

* 单例模式

* @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进行实例化的效果,达到任何时候其实都是同一个对象的效果

测试代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
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这些引用指向的都是同一个对象

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://www.cnblogs.com/xtuxiongda/p/8848924.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java使用静态关键字实现单例模式 https://www.kuaiidc.com/111915.html

相关文章

发表评论
暂无评论