分类:设计模式
单例模式
- 分为饿汉模式和懒汉模式
- 实例步骤:
-构造方法私有化
-声明私有,静态对象
-声明公有方法 - 饿汉模式:
private Singleton(){
}
private static Singleton instanse=new Singleton();
public static Singleton getInstanse(){
return instanse;
}
- 懒汉模式
private Singleton2(){}
private static Singleton2 instanse;
public static Singleton2 getInstanse(){
if(instanse==null){
instanse=new Singleton2();
}
return instanse;
}
- 对比:
-饿汉:类加载慢,运行时快;线程安全
-懒汉:类加载快,运行时慢;线程安全