首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

java惯用设计模式之单例模式

2012-10-07 
java常用设计模式之单例模式-------------------------------- singelton(单例模式) --------------------

java常用设计模式之单例模式
-------------------------------- singelton(单例模式) --------------------------------
基本概念:
Singleton 是一种创建性模型,它用来确保只产生一个实例,并提供一个访问它的全局访问点.对一些类来说,保证只有一个实例是很重要的,比如有的时候,数据库连接或 Socket 连接要受到一定的限制,必须保持同一时间只能有一个连接的存在.运用:
在于使用static变量;
创建类对象,一般是在构造方法中,或用一个方法来创建类对象。在这里方法中,加对相应的判断即可。?单态模式与共享模式的区别:单态模式与共享模式都是让类的实例是唯一的。但单态模式的实现方式是:在类的内部.即在构造方法中,或静态的getInstace方法中,进行判断,若实例存在,则直接返回,不进行创建;共享模式的实现方式是:每次要用到此实例时,先去此hashtable中获取,若获取为空,则生成实例,且将类的实例放在一人hashtable中,若获取不为空,则直接用此实例。???(2)
实例一:
public class Singleton {?
? private static Singleton s;
? public static Singleton getInstance() {
??? if (s == null)
????? s = new Singleton();
??? return s;
? }
}
// 测试类
class singletonTest {
? public static void main(String[] args) {
??? Singleton s1 = Singleton.getInstance();
??? Singleton s2 = Singleton.getInstance();
??? if (s1==s2)
????? System.out.println("s1 is the same instance with s2");
??? else
????? System.out.println("s1 is not the same instance with s2");
? }
}singletonTest运行结果是:
s1 is the same instance with s2(3)
实例二:
class Singleton {
? static boolean instance_flag = false; // true if 1 instance
? public Singleton() {
??? if (instance_flag)
????? throw new SingletonException("Only one instance allowed");
??? else
????? instance_flag = true; // set flag for 1 instance
? }
}转自:http://shenzhenchufa.blog.51cto.com/730213/161581

热点排行