请使用抽象工厂模式实现如下案例:农场中除了像畜牧场一样可以养动物,还可以培养植物,如养马、养牛、种菜、种水果等,所以本实例比前面介绍的畜牧场类复杂。类图如下:
public class Factory {
public static void main(String[] args) {
Farm f1 = new Lisa_Farm(); // 填空(1):使用Lisa_Farm农场或者
f1.newAnimal();
}
}
interface Animal {
public void show();
}
class Horse implements Animal { // 填空(2)
String name;
public Horse(String name) {
this.name = name;
}
public void show() {
System.out.println("一批马被制造了!");
}
}
class Cattle implements Animal { // 填空(3)
String name;
public Cattle(String name) {
this.name = name;
}
public void show() {
System.out.println("一头牛被制造了!");
}
}
interface Plant {
public void show();
}
class Fruit implements Plant { // 填空(4)
String name;
public Fruit(String name) {
this.name = name;
}
public void show() {
System.err.println("水果被制造了!");
}
}
class Vegetable implements Plant {
String name;
public Vegetable(String name) {
this.name = name;
}
public void show() {
System.err.println("蔬菜被制造了!");
}
}
interface Farm {
public Animal newAnimal(); // 填空(5):添加返回Animal的方法
public Plant newPlant(); // 填空(6):添加返回Plant的方法
}
class Lisa_Farm implements Farm {
public Plant newPlant() {
return new Fruit("水果"); // 填空(7)
}
public Animal newAnimal() {
return new Horse("马"); // 填空(8)
}
}
class Tom_Farm implements Farm {
public Plant newPlant() {
return new vegetable("蔬菜"); // 填空(9)
}
public Animal newAnimal() {
return new Cattle("牛"); // 填空(10)
}
}