2007-12-20
单例模式小结
单例模式可以说是我们在日常开发过程中最常用的模式之一,单于单例模式,也有几种不同的实现版本,我们分别来看:
1.最简单,最原始的单例模式:
2.懒汉式:
3.登记式
子类:
4.guice中的单例
1.最简单,最原始的单例模式:
public class EagerSingleton{
private static final EagerSingleton m_instance = new EagerSingleton();
private EagerSingleton() { }
public static EagerSingleton getInstance()
{
return m_instance;
}
}
2.懒汉式:
public class LazySingleton
{
private static LazySingleton
m_instance = null;
private LazySingleton() { }
synchronized public static LazySingleton
getInstance()
{
if (m_instance == null)
{
m_instance = new LazySingleton();
}
return m_instance;
}
}
3.登记式
public class RegSingleton
{
static private HashMap m_registry = new HashMap();
static
{
RegSingleton x = new RegSingleton();
m_registry.put( x.getClass().getName() , x);
}
/**
* 保护的默认构造子
*/
protected RegSingleton() {}
/**
* 静态工厂方法,返还此类惟一的实例
*/
static public RegSingleton getInstance(String name)
{
if (name == null)
{
name = "com.javapatterns.singleton.demos.RegSingleton";
}
if (m_registry.get(name) == null)
{
try
{
m_registry.put( name,
Class.forName(name).newInstance() ) ;
}
catch(Exception e)
{
System.out.println("Error happened.");
}
}
return (RegSingleton) (m_registry.get(name) );
}
/**
* 一个示意性的商业方法
*/
public String about()
{
return "Hello, I am RegSingleton.";
}
}
子类:
public class RegSingletonChild extends RegSingleton
{
public RegSingletonChild() {}
/**
* 静态工厂方法
*/
static public RegSingletonChild getInstance()
{
return (RegSingletonChild)
RegSingleton.getInstance(
"com.javapatterns.singleton.demos.RegSingletonChild" );
}
/**
* 一个示意性的商业方法
*/
public String about()
{
return "Hello, I am RegSingletonChild.";
}
}
4.guice中的单例
public class Singleton {
static class SingletonHolder {
static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
发表评论
提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则
- 浏览: 44148 次
- 性别:


- 详细资料
搜索本博客
我的相册
Faceye基础版(开源)新建标签页
共 24 张
共 24 张
链接
最新评论
-
Faceye基础版(开源)介绍 ...
可以支持其它数据库,数据库无关的,DAO主要为Hibernate,目前已知有朋友 ...
-- by ecsun -
Faceye基础版(开源)介绍 ...
能否支持其他数据库
-- by netwalkerli -
Faceye基础版(开源)介绍 ...
Faceye刚刚起步,还有很多不完善的地方需要进一步完善,可以给大伙带来欢喜,是 ...
-- by ecsun -
Faceye基础版(开源)介绍 ...
谢谢你奉献
-- by lzmhehe -
Faceye基础版(开源)介绍 ...
目前已知已经有很多朋友安装成功了,MySQL数据库导入历来存在编码等一系列问题, ...
-- by ecsun






评论排行榜