模擬一個汽車工廠生產汽車解題提示a)可生產大卡車、大客車、小汽車、跑車等b)不同的車售價不同c)涉及知識點有類、接口、繼承、封裝、多態提示:運用工廠模式的設計模式去做
public interface ICar {
void price();
}
public class Coach implements ICar {
@Override
public void price() {
System.out.printf("2000萬");
}
}
public class Truck implements ICar {
@Override
public void price() {
System.out.printf("1000萬\n");
}
}
public class SUV implements ICar {
@Override
public void price() {
System.out.printf("40萬");
}
}
public class CarFactory {
public static final int TYPE_TRUCK = 1;
public static final int TYPE_COACH = 2;
public static final int TYPE_SUV = 3;
public ICar createCar(int type) {
if (type == TYPE_COACH) {
return new Coach();
} else if (type == TYPE_TRUCK) {
return new Truck();
} else if (type == TYPE_SUV) {
return new SUV();
} else {
// TODO 其他的車
}
}
}