英文名Singleton
最简单的设计模式
应用
当一个类在整个系统生命周期中只需要一个实例的时候使用,并且提供一个给其他类可以访问的接口。
例子
spring中维护的bean,servlet容器中管理的servlet类等。
使用
可以定义一个工厂方法返回该单例类。
class DemoFactory{
private static Demo demo;
static{
demo = new Demo();
}
public DemoFactory(){};
public getDemo(){
return demo;
}
}
或者使用自己的类。
class Demo{
private static Demo demo = new Demo();
private Demo(){};
public static getSingleTon(){
return demo;
}
}
在spring中通过autowired即可,在servlet通常不需要使用者去管理