Singleton pattern

单例模式:即整个应用中该类只产生一个实例化的对象。通过重写构造函数为 private, 使得无法通过关键字 new 来产生实例化对象。在类中实现一个static 的 getIntance() 方法供其他类使用该实例 (例子:--1--> )

[ 必要的时候: 如需要有上限个的多例模式的时候可以通过在单例类中增加个 ArrayList<Object>(考虑到线程安全的话可以使用Vector),并用static 的方式使用 add() 方法实现多例 ]

优点:
1. 单例模式只有一个实例,减少了内存开支、性能开销,(特别是一个对象需要频繁的创建、销毁时)
2. 当一个对象的产生需要较多的资源时,如 读取配置、产生其他依赖对象时,则可以通过在应用启动时
        直接产生一个单例对象,然后永久驻留在内存的方式来解决
        (在java EE中,采用单例模式时需要注意 JVM 垃圾回收机制 mechanism)
3. 单例模式可以避免对资源的多重占用,例如 
        一个写文件动作,由于只有一个实例存在内存中,避免对同一个资源文件的同时写操作。

4. 单例模式可以在系统设置全局的访问点,优化和共享资源访问,
例如可以设计一个单例类,负责所有数据表的映射处理。

缺点:
1. 单例模式一般 没有接口,扩展困难。如需拓展,只能修改代码。
在特殊情况下,单例模式可以实现接口、被继承等
2. 单例模式 对测试时不利的。在并行开发环境中,如果单例模式没有完成,是不能进行测试的,
没有接口也不能使用 mock 的方式虚拟一个对象。

3. 单例模式与单一职责原则有冲突。



Advantage:
1. Singleton has only one instance, that can reduce memory expenses and 
performance overhead.
2. While an object requires/needs more resources, such as reading the configuration,
generate other dependent objects, we can generate a singleton object at the beginning 
of the application startup directly, then permanently residing in memory to solve
the problem. 
(Note: while using this pattern in JavaEE, it's required to pay attention to the JVM
garbage collection mechanism. )
3. Singleton pattern could avoid multiple occupancy of resources. For instance,
A write file action. It could avoid writing the same file due to only one object
exiting in memory.
4. Singleton pattern can set a global access point in the system, optimizing and sharing
the access of resources. For example, designing a singleton class in charge of the 
mapping of all data tables. 


Disadvantage:
1. Singleton pattern don't have an interface generally, therefore it is hard to extend.
Once you want to extend, you have to modify the codes.
2. Singleton pattern is harmful to test. In the concurrent environment, if the singleton 
pattern don't finish first, you cannot test. Due to no have the interface, so that it 
can't virtual an object by the mock.

3. Singleton pattern is conflicted with the single responsibility principle.


--1--> eg:

/**
 * 单例类
 */
public class Emperor {
	private static final Emperor emperor = new Emperor();	// 初始化一个皇帝
	
	private Emperor() {
		// 私有化构造方法,目的是不产生第二个皇帝
		// Making the constructor to private, aim to not get the second instance of Emperor.
	}
	
	// 通过该方法获取实例对象
	// get the instance by this method.
	public static Emperor getInstance() {
		return emperor;
	}
	
	// 单例类中其他方法,尽量是 static 
	// other methods, try best to create it with "static".
	public static void say() {
		System.out.println("I am the only emperor...");
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值