单例模式
一、定义:保证一个类只能有一个实例,并且提供一个访问他的全局访问点。
二、种类:懒汉式单例、饿汉式单例、登记式单例
三、特点:1、单例类只能有一个实例;
2、单例类必须自己自己创建自己的唯一实例;
3、单例类必须给所有其他对象提供这一实例;
四、原理:Singleton通过将构造方法限定为private避免了类在外部被实例化,在同一个虚拟机范围内,Singleton的唯一实例只能通过getInstance()方法访问
五、经典案例:
(此案例为教师课堂所讲案例,president唯一且比较形象)
public class President{
private static President instance = null;
private President(String name){
}
public static getInstance(){
if (instance == null){
President instance = new President()
}
return instance
}
}
多例模式