java中如何实现传入的参数不同,产生的单例也不同
不知道这能否实现,求指导
------解决思路----------------------
你在工厂方法里面 实例多个单列,每个单列的实现都是不一样的。
比如:
public interface Single {
public void doAction();
}
public class SingleA implements Single {
public void doAction() {
}
}
public class SingleB implements Single {
public void doAction() {
}
}
public class SingleFactory {
public static Single getInstance(int type){
if (type == 1) {
return new SingleA ();
}
else if (type == 2) {
return new SingleB ();
}
}
}
这样不知道是不是你想要得。
------解决思路----------------------
补充如果是单列
public class SingleFactory {
static Single a;
static Single b;
public static Single getInstance(int type){
if (type == 1) {
if (a == null) {
a = new SingleA ();
}
return a ;
}
else if (type == 2) {
if (b == null) {
b = new SingleB ();
}
return b;
}
}
}
------解决思路----------------------
典型的工厂模式嘛~~
------解决思路----------------------
引用:补充如果是单列
public class SingleFactory {
static Single a;
static Single b;
public static Single getInstance(int type){
if (type == 1) {
if (a == null) {
a = new SingleA ();
}
return a ;
}
else if (type == 2) {
if (b == null) {
b = new SingleB ();
}
return b;
}
}
}
就是这样~