Java设计模式:农场不同季节生成不同蔬菜水果的一种抽象工厂模式
/*** 农场的抽象。不同季节生产不同的蔬菜和水果。*/public interface Farm {//不同季节,不同蔬菜和水果。int WINTER = 1; //冬季。int SUMMER = 2; //夏季。Fruit makeFruit(); //制造水果。Vegetable makeVegetable();//制造蔬菜。}
/*** 水果的抽象。*/public interface Fruit extends Plant{}
/*** 蔬菜的抽象。*/public interface Vegetable extends Plant{}
/*** 抽象的植物。植物具有的普遍共同行为。*/public interface Plant {void grow();//成长。void ripe();//成熟。}
以上是抽象模型的构建设计。以下是具体的实例实现:
/*** 蔬菜的具体实现。白菜。*/public class Cabbage implements Vegetable {private String name = "白菜";@Overridepublic void grow() {System.out.println(name + "成长");}@Overridepublic void ripe() {System.out.println(name + "成熟");}}
/*** 水果的具体实现。橘子。*/public class Orange implements Fruit {private String name = "橘子";@Overridepublic void grow() {System.out.println(name + "成长");}@Overridepublic void ripe() {System.out.println(name + "成熟");}}
/*** 某一个农场的具体实现。* 不同季节生成相应的蔬菜和水果。*/public class SomeFarmImpl implements Farm {private int season = SUMMER;public SomeFarmImpl(int season) {this.season = season;if (season == WINTER) {System.out.println("冬季");} else if (season == SUMMER) {System.out.println("夏季");}}@Overridepublic Fruit makeFruit() {Fruit fruit = null;if (season == Farm.WINTER) {fruit = new Orange();} else if (season == Farm.SUMMER) {//出产夏季的水果。}return fruit;}@Overridepublic Vegetable makeVegetable() {Vegetable vegetable = null;if (season == Farm.WINTER) {vegetable = new Cabbage();} else if (season == Farm.SUMMER) {//出产夏季的蔬菜。}return vegetable;}}
测试程序:
/*** 测试程序。*/public class Main {public static void main(String[] args) {try {new Main().test();} catch (Exception e) {e.printStackTrace();}}private void test() {Farm farm = new SomeFarmImpl(Farm.WINTER);Fruit fruit = farm.makeFruit();fruit.grow();fruit.ripe();Vegetable vegetable = farm.makeVegetable();vegetable.grow();vegetable.ripe();}}
输出:
冬季橘子成长橘子成熟白菜成长白菜成熟