单例模式比较容易理解,狭义的单例模式就是一个class只有产生一个对象,广义的是数量确定(n)个对象.
单例模式适用场景是: 业务场景需要某个类只能有一个实例.或者资源限制只能有固定数量的某个对象比如文件读写对象,数据库读写对象等。
实现方法:
用static方式实现:
public class FileReader implements MyReader {
private static FileReader o;
static{
o = new FileReader();
}
public static FileReader getInstance(){
return o;
}
public Object doRead() {
// TODO Auto-generated method stub
return o.doRead0();
}
private Object doRead0(){
return "I am doing the reading and I am the reader "+o.hashCode();
}
}
public class MainTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
FileReader fr = FileReader.getInstance();
Object obj = fr.doRead();
System.out.println(obj);
FileReader fr2 = FileReader.getInstance();
obj = fr2.doRead();
System.out.println(obj);
}
}
获取实例时如果实例为空就创建实例:
public class FileReader2 implements MyReader {
private FileReader2 fr;
public synchronized FileReader2 getInstance(){//synchronized 关键字防止多线程出错,但这样有点影响性能。
if(fr == null){
fr = new FileReader2();
}
return fr;
}
public Object doRead() {
// TODO Auto-generated method stub
return fr.doRead0();
}
public Object doRead0(){
return "I am the FileReader2 :"+fr.hashCode();
}
}
用池实现N个实例的广义单例模式:
public class FileReaderPool {
private int maxNum = 3;
private ArrayList<FileReader> al = new ArrayList<FileReader>();
public synchronized FileReader getInstance(){
if(al.size()<this.maxNum){
FileReader fr = new FileReader();
al.add(fr);
}
return al.get((new Random()).nextInt(al.size()));
}
}