一、概述
作为对象的创建模式,多例模式中的多例类可以有多个实例,而且多例类必须自己创建、管理自己的实例,并向外界提供自己的实例
二、代码
1.有限多例模式
/*有限多例模式*/
public class MultiObj {
private static MultiObj obj1 = new MultiObj();
private static MultiObj obj2 = new MultiObj();
private MultiObj(){
}
public static MultiObj getInstance(int num){
if(num == 1){
return obj1;
}
return obj2;
}
}
2.无限多例模式
/*无上限多例模式*/
public class MultiObj {
private String key;
private String value;
private MultiObj(String key, String value) {
this.key = key;
this.value = value;
}
private MultiObj() {
}
private static HashMap
mHasMap = new HashMap<>();
public static MultiObj getInstance(String key,String value){
if(mHasMap.get(getKeyCode(key, value)) != null){
return mHasMap.get(getKeyCode(key, value));
}
return new MultiObj(key,value);
}
private static StringBuffer getKeyCode(String key,String value){
return new StringBuffer(key).append("_").append(value);
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}