本文为大家分享了使用静态关键字实现单例模式的具体代码,供大家参考,具体内容如下
单例模式:只能获得某个类的唯一一个实例
单例模式,不管什么时间点得到的对象都是同一个对象
看下面代码:
?
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);
}
}
|
结果如下:
该结果表明:single、single2、single3这些引用指向的都是同一个对象
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。
原文链接:https://www.cnblogs.com/xtuxiongda/p/8848924.html
相关文章
猜你喜欢
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-29 69
-
2025-05-29 87
-
2025-05-25 34
-
2025-05-27 27
-
2025-05-25 49
热门评论