For a detailed explanation of the factory method pattern, see the author’s blog
Design patterns part 2 creative design patterns chapter 5 factory method patterns (A: C++ implementation)
This article is a Java implementation of the Factory Method pattern.
Step 1: Abstract the product
package com;
public interface Product {
public void show(a);
}
Copy the code
Step 2: Specific products
package com;
public class ConcreteProduct1 implements Product{
public void show(a)
{
System.out.println("I'm ConcreteProduct1"); }}package com;
public class ConcreteProduct2 implements Product{
public void show(a)
{
System.out.println("I'm ConcreteProduct2"); }}Copy the code
Step 3: Abstract factory
package com;
public interface Creator {
public Product CreateProduct(a);
}
Copy the code
Step 4: Specific factory
package com;
public class ConcreteCreator1 implements Creator{
@Override
public Product CreateProduct(a) {
return newConcreteProduct1(); }}Copy the code
package com;
public class ConcreteCreator2 implements Creator{
@Override
public Product CreateProduct(a) {
return newConcreteProduct2(); }}Copy the code
Step 5: Test
package com;
public class Main {
public static void main(String[] args) {
Creator factoryA = new ConcreteCreator1 ();
Product productA = factoryA.CreateProduct();
productA.show();
Creator factoryB = newConcreteCreator2 (); Product productB = factoryB.CreateProduct(); productB.show(); }}Copy the code
The result is as follows: