标签:
简单工厂模式又称为静态工厂方法模式,属于创建型模式。public class VegetableFarm {
public static Vegetable getVegetable(String vegetableName) {
switch (vegetableName.toLowerCase()) {
case "carrot":
return new Carrot();
case "potato":
return new Potato();
case "tomato":
return new Tomato();
}
throw new UnsupportedOperationException();
}
}蔬菜承担抽象产品角色,定义所有蔬菜共有的属性和行为:public abstract class Vegetable {
protected double weight = 0;
public double getWeight() {
return weight;
}
}胡萝卜、土豆和番茄承担具体产品角色,是蔬菜农场实际生产的产品:public class Carrot extends Vegetable {
}
public class Potato extends Vegetable {
}
public class Tomato extends Vegetable {
}消费者承担调用者角色,只需要调用工厂方法就可以直接获取具体产品:Vegetable vegetable = VegetableFarm.getVegetable("Tomato");
标签:
原文地址:http://blog.csdn.net/magnificent_tony/article/details/43835697