多例设计模式与单例设计模式的共同点:
1.他们的构造方法都私有化;
2.类中都有static的getter方法,用来获取私有的对象属性
多例设计模式:
class Driver {
private String driver;
public static final int MALE_DRIVER = 1;
public static final int FEMALE_DRIVER = 2;
public static final Driver MALE = new Driver("男司机");
public static final Driver FEMALE = new Driver("女司机");
//私有的构造方法
private Driver(String driver) {
this.driver = driver;
}
//static的getter方法
public static Driver getInstance(int num) {
if (num == MALE_DRIVER) {
return MALE;
}
if (num == FEMALE_DRIVER) {
return FEMALE;
}
else
return null;
}
//toString方法
public String toString(){
return this.driver;
}
}
public class MultitonTest {
public static void main(String[] args){
Driver male = Driver.getInstance(Driver.MALE_DRIVER);
System.out.println(male);
}
}