Compared with the simple factory model, the factory method mode has the advantage of better expansion. If another product is added, the core factory class needs to be modified for the simple factory model, however, the factory method mode is not required. In the factory method mode, the core factory class is no longer responsible for creating all products. Instead, the specific creation work is handed over to the class for implementation, your core class becomes an abstract factory role.
This further abstract result allows the system to introduce new products without modifying the factory class. This mode involves four roles:
A concrete creator is a product. The Code is as follows:
1: Abstract Factory:
public interface Creator { public Product factory();}
2: Abstract Product
public interface Product { void plant();}
3: Specific Factory 1:
public class ConcreteCreator1 implements Creator { @Override public Product factory() { return new ConcreteProduct1(); }}
4: specific factory 2:
public class ConcreteCreator2 implements Creator{ @Override public Product factory() { return new ConcreteProduct2(); }}
5: Product 1:
public class ConcreteProduct1 implements Product { public ConcreteProduct1() { System.out.println("ConcreteProduct1.ConcreteProduct1"); } @Override public void plant() { System.out.println("ConcreteProduct1.plant"); }}
6: Product 2:
public class ConcreteProduct2 implements Product { public ConcreteProduct2() { System.out.println("ConcreteProduct2.ConcreteProduct2"); } @Override public void plant() { System.out.println("ConcreteProduct2.plant"); }}
7: Test class:
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(); }}
8: The running result is as follows:
ConcreteProduct1.ConcreteProduct1ConcreteProduct1.plantConcreteProduct2.ConcreteProduct2ConcreteProduct2.plantProcess finished with exit code 0
9: This project is built based on maven and the testing framework is JUnit.
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency>