设计模式之简单工厂模式

简单工厂模式又称为静态工厂方法模式,属于创建型模式。结构简单工厂模式包括工厂、抽象产品和具体产品三个角色。优点缺点使用场景工厂负责创建的具体产品种类少,不需要经常增加新的具体产品,不需要经常修改具体产品的创建逻辑。调用者直接获取具体产品,不关心具体产品的创建逻辑。实例日常生活中我们经常需要购买蔬菜,但是我们不关心蔬菜的种植过程,只需要消费市场上的蔬菜产品。蔬菜农场承担工厂角色,负责生产具体蔬菜: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");

当遗忘变成另一种开始,淡了回忆,痛最真实…

设计模式之简单工厂模式

相关文章:

你感兴趣的文章:

标签云: