1.单例模式的定义:保证一个类仅有一个实例,并一个访问它的全局访问点。
2.懒汉式:
public class Appconfig_lazy {
private String a,b;
private static Appconfig_lazy instance = null;
public static synchronized Appconfig_lazy getInstance(){
if (instance == null) {
instance = new Appconfig_lazy();
}
return instance;
}
public String getA() {
return a;
}
public String getB() {
return b;
}
private Appconfig_lazy(){
readConfig();
}
private void readConfig() {
// TODO Auto-generated method stub
this.a = "a";
this.b = "b";
System.out.println("----");
}
}
3.恶汉式:
public class Appconfig_hun {
private String a, b;
private static Appconfig_hun instance = new Appconfig_hun();
public static Appconfig_hun getInstance() {
return instance;
}
private Appconfig_hun() {
readConfig();
}
private void readConfig() {
// TODO Auto-generated method stub
this.a = "1";
this.b = "2";
}
public String getA() {
return a;
}
public String getB() {
return b;
}
}
3.命名方式:根据创建对象实例的时机,如果装载类的时候就创建叫做恶汉式;如果等到要用时再创建叫做懒汉式。
4.模式功能:保证类在运行时只会有一个实例。
5.模式范围:在Java虚拟机范围内,每个ClassLoader装载改类,都会产生实例。
6.懒汉式包含了延迟加载和缓存的思想。
7.优缺点:①时间空间:懒汉式是时间换取空间;恶汉式是空间换取时间。
②线程安全:不加同步的懒汉式不安全,可能导致并发。恶汉式安全。
③懒汉式单使用synchronized会降低访问速度。
8.懒汉式的优化,避免性能的过多影响:①双重检查加锁:使用关键词volatile。不是每次进入getInstance都会同步,而是先不同步,进入方法过后,先检查实例是否存在,如果不存在再进入同步块,这是第一重检查。进入同步块后再次检查实例是否存在,不存在就创建实例,这是第二重检查。
public class Appconfig_lazy_double {
private String a, b;
private volatile static Appconfig_lazy_double instance = null;
public static Appconfig_lazy_double getInstance() {
if (instance == null) {
synchronized (Appconfig_lazy_double.class) {
instance = new Appconfig_lazy_double();
}
}
return instance;
}
public String getA() {
return a;
}
public String getB() {
return b;
}
private Appconfig_lazy_double() {
readConfig();
}
private void readConfig() {
// TODO Auto-generated method stub
this.a = "a";
this.b = "b";
System.out.println("----");
}
}
②Lazy initialzation holder class:结合类级内部类和多线程缺省同步锁。
public class Appconfig_lazy {
private String a,b;
private static class holder{
private static Appconfig_lazy instance = new Appconfig_lazy();
}
public static synchronized Appconfig_lazy getInstance(){
return holder.instance;
}
public String getA() {
return a;
}
public String getB() {
return b;
}
private Appconfig_lazy(){
readConfig();
}
private void readConfig() {
// TODO Auto-generated method stub
this.a = "a";
this.b = "b";
System.out.println("----");
}
}
9.单例模式的本质:控制实例数量。