单例设计、多例设计(2021-11-02)
单例/多例设计,是控制实例化对象个数的设计操作。
单例设计:将构造方法设为private,定义1个private static final的对象和对应static的get方法。多例设计只是定义多个private static final的对象。
单例设计:
package package1;
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton(){};
public static Singleton getInstance(){
return INSTANCE;
}
public void print(){
System.out.println("对象内的打印方法");
}
}
多例设计:
package package1;
public class Choice {
private String color;
private static final Choice RED = new Choice("红色");
private static final Choice GREEN = new Choice("绿色");
private static final Choice BLUE = new Choice("蓝色");
private Choice(String color){
this.color=color;
}
public static Choice getInstance(String str){
switch(str){
case "red": return RED;
case "green": return GREEN;
case "blue": return BLUE;
default: return null;
}
}
public String toString(){
return this.color;
}
}

浙公网安备 33010602011771号