单例设计模式
来源:互联网 发布:移动宽带网络客服电话 编辑:程序博客网 时间:2024/05/07 13:52
/*
* 设计模式:对问题行之有效的解决方式,其实它是一种思想.
* 1.单例设计模式:
* 解决的问题:就是可以保证一个类在内存中的对象的唯一性.
*
* 必须对多个程序使用同一个配置信息对象时,就需要保证该对象的唯一性.
* 如何保证对象的唯一性:
* 1.不允许其他程序用new创建该类对象.
* 2.在该类创建一个本类实例.
* 3.对外提供一个方法让其他程序可以获得该对象.
*
* 步骤:
* 1.私有化该类构造函数.
* 2.通过new在本类中创建一个本类对象.
* 3.定义一个公有的方法,将创建的对象返回.
*/
public class SingleDemo { public static void main(String[] args) {// Single s1 = Single.getInstance() ;// Single s2 = Single.getInstance() ;// System.out.println(s1==s2); Test t1 = Test.getInstance() ; Test t2 = Test.getInstance() ; t1.setNum(10); t2.setNum(20); System.out.println(t1.getNum()); System.out.println(t2.getNum()); }}//饿汉式class Single { //类一旦加载,对象就已经存在了. private static Single s = new Single() ; //通过new在本类中创建一个本类对象. private Single() { //私有化该类构造函数 } public static Single getInstance() { //定义一个公有的方法,将创建的对象返回. return s; }}//懒汉式class Single_2 { //类加载的时候,没有对象,只有调用了getInstance方法时,才会创建对象. //延迟加载形式. private static Single_2 s = null ; private Single_2() { } public static Single_2 getInstance() { if(s==null) { s = new Single_2() ; } return s; }}class Test { private int num ; private static Test t = new Test() ; private Test() {} public static Test getInstance() { return t ; } public int getNum() { return num; } public void setNum(int num) { this.num = num; }}
1 0
- 设计模式--单例
- 单例设计模式
- 设计模式----单例
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 设计模式-单例
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- 单例设计模式
- /lib64/libc.so.6: version `GLIBC_2.14' not found问题
- mysql实现hash分表
- Hibernate
- 学习UML后的一点总结
- 如何编写一个简单群聊
- 单例设计模式
- electron+react+redux+material-ui桌面应用小结
- 删除文件夹
- Faster RCNN代码理解(Python)
- lintcode,寻找旋转排序数组中的最小值
- 程序的内存分配
- LCA(st算法)
- 《Effective Java》第3章 对于所有对象都通用的方法
- jQuery全选和范选,按钮样式变化及取选中项的值