设为首页 加入收藏

TOP

单例模式的两种形式(恶汉式,懒汉式)
2015-11-21 01:02:02 来源: 作者: 【 】 浏览:2
Tags:单例 模式 形式 懒汉

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

写单例模式的步骤:

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;
	}
}

单例模式的运行原理:

?

\

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇求数组中出现一次的数字 下一篇poj 1325(二分图匹配)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: