第五篇写了关于简单工厂模式,链接地址:http://www.cnblogs.com/lay2017/p/7573805.html
但是我们的项目有时候简单工厂并不能满足,可能需要多个简单工厂,那么这时候如果我们用一个超级工厂来管理这些简单工厂是不是可以呢?这就是抽象工厂模式,如图:
抽象工厂模式能够帮助我们解决接口选择的问题,提供一个清晰的入口。具体代码如下:
/** * 抽象工厂 * @author lay */ public class SuperFactoryDemo { public static void main(String[] args) { SuperFactory superFactory = FactoryProducer.getFactory("fire"); FireParent fireParent = superFactory.getFire("fireChild1"); fireParent.doSth(); superFactory = FactoryProducer.getFactory("sunshine"); SunshineParent sunshineParent = superFactory.getSunshine("sunshineChild1"); sunshineParent.doSth(); } } // 提供获取工厂的方法 class FactoryProducer{ public static SuperFactory getFactory(String factoryName){ SuperFactory superFactory = null; switch (factoryName) { case "fire": superFactory = new FireFactory(); break; case "sunshine": superFactory = new SunshineFactory(); break; default: break; } return superFactory; } } // 建立超级工厂 interface SuperFactory{ public FireParent getFire(String firename); public SunshineParent getSunshine(String sunshineName); } // 建立第一个简单工厂 class FireFactory implements SuperFactory{ public FireParent getFire(String fireName){ FireParent fireParent = null; switch (fireName) { case "fireChild1": fireParent = new FireChild1(); break; case "fireChild2": fireParent = new FireChild2(); break; default: break; } return fireParent; } @Override public SunshineParent getSunshine(String sunshineName) { return null; } } interface FireParent{ public void doSth(); } class FireChild1 implements FireParent{ @Override public void doSth() { System.out.println("fire child 1"); } } class FireChild2 implements FireParent{ @Override public void doSth() { System.out.println("fire child 2"); } } // 建立第二个工厂 class SunshineFactory implements SuperFactory{ public SunshineParent getSunshine(String sunshineName){ SunshineParent sunshineParent = null; switch (sunshineName) { case "sunshineChild1": sunshineParent = new SunshineChild1(); break; case "sunshineChild2": sunshineParent = new SunshineChild2(); break; default: break; } return sunshineParent; } @Override public FireParent getFire(String firename) { return null; } } interface SunshineParent{ public void doSth(); } class SunshineChild1 implements SunshineParent{ @Override public void doSth() { System.out.println("sunshine child 1"); } } class SunshineChild2 implements SunshineParent{ @Override public void doSth() { System.out.println("sunshine child 2"); } }
抽象工厂很好地组织了对象的创建,但问题也是很明显的,由于它是多个工厂的结合,所以当这个超级工厂非常大的时候,改动起来就会很不方便,你不仅需要改动具体的业务内容,你还要改动工厂。
时间: 2024-12-15 06:34:34