单例模式
来源:互联网 发布:已恢复的网络购彩 编辑:程序博客网 时间:2024/05/22 05:25
什么是单例模式:
Singleton 是一种创建性模型,它用来确保只产生一个实例,并提供一个访问它的全局访问点.对一些类来说,保证只有一个实例是很重要的,比如有的时候,数据库连接或 Socket 连接要受到一定的限制,必须保持同一时间只能有一个连接的存在.运用场合:
在于使用static变量;
创建类对象,一般是在构造方法中,或用一个方法来创建类对象。在这里方法中,加对相应的判断即可。
在于使用static变量;
创建类对象,一般是在构造方法中,或用一个方法来创建类对象。在这里方法中,加对相应的判断即可。
单态模式与共享模式的区别:
单态模式与共享模式都是让类的实例是唯一的。
但单态模式的实现方式是:
在类的内部.即在构造方法中,或静态的getInstace方法中,进行判断,若实例存在,则直接返回,不进行创建;
共享模式的实现方式是:
每次要用到此实例时,先去此hashtable中获取,若获取为空,则生成实例,且将类的实例放在一人hashtable中,若获取不为空,则直接用此实例。
代码实现:
实例一:
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");
}
}
实例一:
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
实例二:
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
}
}
s1 is the same instance with s2
实例二:
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
}
}
0 0
- 单例、单例模式
- 单例模式-多线程单例模式
- 单件模式(单例模式)
- 设计模式------单例模式
- 设计模式------单例模式
- 设计模式-单例模式
- 设计模式 - 单例模式
- 设计模式---单例模式
- 设计模式---单例模式
- PHP模式-单例模式
- 【设计模式】单例模式
- 设计模式-单例模式
- 设计模式----单例模式
- 设计模式--单例模式
- 设计模式-单例模式
- 单例模式(单子模式)
- 设计模式-单例模式
- [设计模式] 单例模式
- Spring整合MongoDB
- Android 自定义控件打造史上最简单的侧滑菜单01
- 最大似然估计(Maximum likelihood estimation)
- STL容器之优先队列
- Fragment生命周期
- 单例模式
- 深入理解GCD(一)
- js获取当前时间戳
- 使用FormData对象
- Postgres的Standby数据库搭建,异步流复制示例及同步流复制实例
- std::set
- 电阻屏和电容屏的区别
- git 本地代码仓库搭建
- java 异常(二)代码