首页 > 其他 > 详细

单例模式的两种形式(恶汉式,懒汉式)

时间:2015-05-17 23:39:41      阅读:306      评论:0      收藏:0      [点我收藏+]

单例模式的特点:解决了一个类在内存的唯一性,这个类的对象只有一个。

写单例模式的步骤:

1. 私有修饰构造方法

2. 在本类的成员位置, new 自己类的对象

3. 提供一个静态方法,返回本类的对象

A: 恶汉式

package demo01;
/**
 * 单例设计模式恶汉式
 * @author Administrator
 *
 */
public class SingleDesignModel1 {
	//私有构造方法
	private SingleDesignModel1(){
	}
	//在自己的成员变量的位置,new 自己
	private static final SingleDesignModel1 singleDesignModel1=new SingleDesignModel1();
	//提供一个静态方法,返回一个本类对象
	public static SingleDesignModel1 getInstance(){
		return singleDesignModel1;
	}
}

B:懒汉式

package demo01;
/**
 * 单例模式的懒汉式
 * @author Administrator
 *
 */
public class SingleDesignModel2 {
	private static SingleDesignModel2 singleDesignModel2=null;
	private SingleDesignModel2(){
		
	}
	public static SingleDesignModel2 getInstance(){
		if(singleDesignModel2==null){
			singleDesignModel2=new SingleDesignModel2();
		}
		return singleDesignModel2;
	}
}

单例模式的运行原理:

技术分享

单例模式的两种形式(恶汉式,懒汉式)

原文:http://blog.csdn.net/u014010769/article/details/45797661

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!