请使用抽象工厂模式实现如下案例:农场中除了像畜牧场一样可以养动物,还可以培养植物,如养马、养牛、种菜、种水果等,所以本实例比前面介绍的畜牧场类复杂。类图如下:

请使用抽象工厂模式实现如下案例:农场中除了像畜牧场一样可以养动物,还可以培养植物,如养马、养牛、种菜、种水果等,所以本实例比前面介绍的畜牧场类复杂。类图如下:

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)
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值