在实际开发中,单例模式是一种很有用的设计模式,能很好的解决我们只需要类的一个实例的情况,单例模式常见的两种实现方式如下
懒汉式:
class Test {
private static Test _instance;
private Test() {
}
/**
*
* @return 返回Test唯一实例
*/
public synchronized static Test getInstance() {
if (null == _instance) {
_instance = new Test();
}
return _instance;
}
}
饿汉式:
class Test {
private static Test _instance = new Test();
private Test() {
}
/**
*
* @return 返回Test唯一实例
*/
public static Test getInstance() {
return _instance;
}
}
按照上面这种写法,几乎所有单例都需要这段基本一样的代码,本文将介绍另外一种实现,可实现代码的复用,实现技巧:将单例看成是一种性质,而JDK1.5+的注解这一特性能很好的帮助我们解决这一需求,将类标记为单例。
1. 首先定义单例注解,注解的作用就是将类标记为单例
import java.lang.annotation.Documented;
import jav