设计模式之工厂方法模式
工厂方法模式
- 工厂方法模式结构图
-
示例代码:
public interface Product { void doSomething(); } public class ProductA implements Product{ @Override public void doSomething() { System.out.println("这是产品A!"); } } public class ProductB implements Product{ @Override public void doSomething() { System.out.println("这是产品B!"); } } public interface Factory { Product makeProduct(); } public class FactoryA implements Factory{ @Override public Product makeProduct() { return new ProductA(); } } public class FactoryB implements Factory{ @Override public Product makeProduct() { return new ProductB(); } } public class FactoryMethodTest { public static void main(String[] args) { FactoryA factory = new FactoryA(); Product product = factory.makeProduct(); product.doSomething(); } }
3.总结:
优点:灵活性强,新增产品只需添加相应工厂即可,解偶框架,符合迪米特法则,依赖倒置原则和里氏替换原则.
缺点:类增多,增加复杂度,增加了系统的抽象性和理解难度.