一、单例模式
该模式的特点是类加载时没有生成单例,只有当第一次调用 getlnstance 方法时才去创建这个单例。单例模式有如下特点:
- 单例类只有一个实例对象;
- 该单例对象必须由单例类自行创建;
- 单例类对外提供一个访问该单例的全局访问点
代码如下:
1、懒汉式
public class Person{
private static volatile Person instance = null;
private Person(){}; //私有的空参构造器,避免外部调用
public synchronized Person getInstance(){
if(instance == null){
return new Person();
}else{
return instance;
}
}
}
2、饿汉式
public class Person{
private static final Person instance = new Person();
private Person(){
}
public Person getInstance(){
return instance;
}
}
例1:用单例模式模拟产生猪八戒对象
//饿汉式
public class Zhubajie{
private static final String name = "zhubajie";
private static final String otherName = "天蓬元帅";
private zhubajie(){};
private static final Zhubajie instance = new Zhubajie();
public Zhubajie getInstance(){
return instance;
}
public String getName(){
return name;
}
public String getOtherName(){
return otherName;
}
}
//懒汉式
public class Zhubajie{
private static final String name = "zhubajie";
private static final String otherName = "天蓬元帅";
private static volatile Zhubajie = null;
private Zhubajie(){};
public Zhubajie getInstance(){
if(instance == null){
return new Zhubajie();
}else{
return instance;
}
}
public String getName(){
return name;
}
public String getOtherName(){
return otherName;
}
}
未完待续。。。。。