设计模式学习之旅-抽象工厂模式
一、抽象工厂模式
抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。
二、介绍
意图:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
主要解决:主要解决接口选择的问题。
何时使用:系统的产品有多于一个的产品族,而系统只消费其中某一族的产品,通过产品组和产品级别即可定义某一具体产品。
如何解决:在一个产品族里面,定义多个产品。
关键代码:在一个工厂里聚合多个同类产品。
三、代码演示
1 public abstract class AbstractFactory { 2 3 abstract Sex getSex(String sex); 4 5 abstract Animal getAnimal(String animal); 6 }
1 public class AnimalFactory extends AbstractFactory { 2 @Override 3 Sex getSex(String sex) { 4 return null; 5 } 6 7 @Override 8 public Animal getAnimal(String animalKey) { 9 if (animalKey == null) { 10 return null; 11 } else { 12 if ("dog".equals(animalKey)) { 13 return new Dog(); 14 } 15 if ("cat".equals(animalKey)) { 16 return new Cat(); 17 } 18 if ("rabbit".equals(animalKey)) { 19 return new Rabbit(); 20 } 21 return null; 22 } 23 } 24 }
1 public class SexFactory extends AbstractFactory { 2 3 @Override 4 public Sex getSex(String sex) { 5 if (sex == null) { 6 return null; 7 } else { 8 if ("male".equals(sex)) { 9 return new Male(); 10 } 11 if ("female".equals(sex)) { 12 return new Female(); 13 } 14 } 15 return null; 16 } 17 18 @Override 19 Animal getAnimal(String animal) { 20 return null; 21 } 22 }
1 public class FactoryProducer { 2 public static AbstractFactory getFactory(String factory){ 3 if("sex".equals(factory)){ 4 return new SexFactory(); 5 } 6 if("animal".equals(factory)){ 7 return new AnimalFactory(); 8 } 9 return null; 10 } 11 }
1 public interface Animal { 2 void eat(); 3 }
1 public class Cat implements Animal { 2 @Override 3 public void eat() { 4 System.out.println("猫吃鱼"); 5 } 6 }
1 public class Dog implements Animal { 2 @Override 3 public void eat() { 4 System.out.println("狗吃骨头"); 5 } 6 }
1 public class Rabbit implements Animal { 2 @Override 3 public void eat() { 4 System.out.println("兔子吃胡萝卜"); 5 } 6 }
1 public interface Sex { 2 void getSex(); 3 }
1 public class Male implements Sex { 2 @Override 3 public void getSex() { 4 System.out.println("It's male"); 5 } 6 }
1 public class AbstractFactoryDemo { 2 3 public static void main(String[] args) { 4 //获取性别工厂 5 AbstractFactory sexFactory = FactoryProducer.getFactory("sex"); 6 7 //获取动物工厂 8 AbstractFactory animalFactory = FactoryProducer.getFactory("animal"); 9 10 //获取雄性 11 Sex male = sexFactory.getSex("male"); 12 male.getSex(); 13 14 //获取雌性 15 Sex female = sexFactory.getSex("female"); 16 female.getSex(); 17 18 //获取狗狗 19 Animal dog = animalFactory.getAnimal("dog"); 20 dog.eat(); 21 22 //获取猫咪 23 Animal cat = animalFactory.getAnimal("cat"); 24 cat.eat(); 25 26 //获取兔兔 27 Animal rabbit = animalFactory.getAnimal("rabbit"); 28 rabbit.eat(); 29 } 30 }
运行结果
It's male
It's female
狗吃骨头
猫吃鱼
兔子吃胡萝卜