public class DesignPattern { public static void main(String[] args) { //抽象工厂允许获取不同种类的工厂,并进行工厂方法的调用,获取想要的对象 FactoryProducer producer = new FactoryProducer(); //获取pizza的制作工厂 AbstractFactory pizzaFactory = producer.getFactory("PizzaFactory"); //pizza的北京口味 Pizza beijingPizza = pizzaFactory.getPizza("BeijingPizza"); beijingPizza.taste(); //pizza的南京口味 Pizza nanjingPizza = pizzaFactory.getPizza("NanjingPizza"); nanjingPizza.taste(); //获取面包的制作工厂 AbstractFactory breadFactory = producer.getFactory("BreadFactory"); //面包的北京口味 Bread beijingBread = breadFactory.getBread("BeijingBread"); beijingBread.taste(); //面包的南京口味 Bread nanjingBread = breadFactory.getBread("NanjingBread"); nanjingBread.taste(); } } interface Pizza{ //不同的pizza有不同的口味 void taste(); } interface Bread{ //不同的面包有不同的口味 void taste(); } class BeijingPizza implements Pizza{ @Override public void taste() { System.out.println("北京pizza口味"); } } class NanjingPizza implements Pizza{ @Override public void taste() { System.out.println("南京pizza口味"); } } class BeijingBread implements Bread{ @Override public void taste() { System.out.println("北京面包的口味"); } } class NanjingBread implements Bread{ @Override public void taste() { System.out.println("南京面包的口味"); } } //抽象工厂 abstract class AbstractFactory{ public abstract Pizza getPizza(String type); public abstract Bread getBread(String type); } //pizza工厂 class PizzaFactory extends AbstractFactory{ @Override public Pizza getPizza(String type) { Pizza pizza = null; if(type == null){ System.out.println("传入参数有误"); }else{ try { pizza = (Pizza)Class.forName("com.zhouge.design.test." + type).newInstance(); } catch (Exception e) { System.out.println("输入信息有误"); } } return pizza; } @Override public Bread getBread(String type) { return null; } } //面包工厂 class BreadFactory extends AbstractFactory{ @Override public Pizza getPizza(String type) { return null; } @Override public Bread getBread(String type) { Bread bread = null; if(type == null){ System.out.println("传入参数有误"); }else{ try { bread = (Bread) Class.forName("com.zhouge.design.test." + type).newInstance(); } catch (Exception e) { System.out.println("输入信息有误"); } } return bread; } } //工厂的工厂 class FactoryProducer{ public AbstractFactory getFactory(String factoryName){ AbstractFactory factory = null; if(factoryName == null){ System.out.println("工厂名不能为空"); }else { try { factory = (AbstractFactory) Class.forName("com.zhouge.design.test." + factoryName).newInstance(); } catch (Exception e) { System.out.println("该工厂不存在"); } } return factory; } }