今天朋友找我给做道题,双例模式,我是没听说过,都说是单例模式和多例模式,
也不知道双例模式什么时候用,就简单写了一个案例,不知道对不对,个人感觉蛮对的,双例就是单例+单例,废话不说了!!!!
/*
*单例模式
调用方法
Singleton singleton = Singleton.getSingleton();
singleton.getValue("我是单例模式");
*/
public class Singleton {
private static Singleton singleton = null;
public static Singleton getSingleton(){
if(singleton==null){
return singleton = new Singleton();
}else{
return singleton;
}
} public String getValue(String name){
return name;
}
} /*
*双例模式,如果是三例模式就吧len参数改成3
调用方法
Doubleton doubleton = Doubleton.getDoubleton();
doubleton.getValue("我有两个实例!");
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Random; public class Doubleton { private static List<Doubleton> list = new ArrayList<Doubleton>();
private static int len = 2;
static{
for(int i=0;i<len;i++){
list.add(new Doubleton());
}
}
public static Doubleton getDoubleton (){
Random random = new Random();
int current = random.nextInt(len);
return (Doubleton)list.get(current);
} public String getValue(String name){
return name;
}
}
希望大牛们给指点指点对不对,在此感谢!!!!