标签:
工厂方法模式相对于简单工厂模式的长处是为了更好的拓展,当假设再新加一种产品,对于简单工厂模式来说须要改动核心的工厂类,但对于工厂方法模式则不须要,在工厂方法模式中核心的工厂类不再负责创建全部产品的创建。而是将详细创建的工作交给了了类去实现,自己的核心类则变成一个抽象的工厂角色。
这样的 进一步的抽象的结果 是能够同意系统在不改动工厂类的前提下引进新的产品。此模式涉及到四种 角色。分别例如以下:
抽象 工厂(Creator) 详细工厂(Concrete creator) 抽像产品(Product) 详细产品(Concrete Product),详细代码例如以下:
1:抽象工厂:
public interface Creator { public Product factory(); }
public interface Product { void plant(); }
public class ConcreteCreator1 implements Creator { @Override public Product factory() { return new ConcreteProduct1(); } }
public class ConcreteCreator2 implements Creator{ @Override public Product factory() { return new ConcreteProduct2(); } }
public class ConcreteProduct1 implements Product { public ConcreteProduct1() { System.out.println("ConcreteProduct1.ConcreteProduct1"); } @Override public void plant() { System.out.println("ConcreteProduct1.plant"); } }
public class ConcreteProduct2 implements Product { public ConcreteProduct2() { System.out.println("ConcreteProduct2.ConcreteProduct2"); } @Override public void plant() { System.out.println("ConcreteProduct2.plant"); } }
public class Tests { @Test public void testFactoryMethod() { ConcreteCreator1 concreteCreator1 = new ConcreteCreator1(); Product product1 = concreteCreator1.factory(); product1.plant(); ConcreteCreator2 concreteCreator2 = new ConcreteCreator2(); Product product2 = concreteCreator2.factory(); product2.plant(); } }
ConcreteProduct1.ConcreteProduct1 ConcreteProduct1.plant ConcreteProduct2.ConcreteProduct2 ConcreteProduct2.plant Process finished with exit code 0
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency>
工厂方法模式(factory method pattern)
标签:
原文地址:http://www.cnblogs.com/mengfanrong/p/5150264.html