Factory Method Pattern - Factory Method
The Factory Method pattern defines an interface for creating objects and lets subclasses decide which class to instantiate. The factory method allows the specific content of instantiation to be handed over to the subclass factory for processing.
Product abstract class
The factory is used to generate instances. Let's abstract these instances first and define them as Product. Product has a feature that it can be used, that is, there is a use() method
public abstract class Product { public abstract void use(); }
Factory abstract class
Factory is an abstract class and an abstract template for factories that generate concrete instances.
public abstract class Factory { /** * Define the execution template here */ public final Product create(String owner) { Product p = createProduct(owner); registerProduct(p); return p; } /** * Leave it to subclasses to implement */ protected abstract Product createProduct(String owner); /** * Leave it to subclasses to implement */ protected abstract void registerProduct(Product p); }
IDCard class
An ID card, also known as an ID card, is defined as a product and inherits from the Product class.
public class IDCard extends Product { private String owner; public IDCard(String owner) { this.owner = owner; } @Override public void use() { System.out.println(owner + "的ID卡"); } public String getOwner() { return owner; } }
IDCardFactory class
This factory class is a factory used to generate IDCard instances. It implements methods that are not implemented in the abstract class of the template factory Factory, that is, the details are controlled by themselves, and the general execution template is uniformly defined by the Factory class.
public class IDCardFactory extends Factory { private ArrayList<String> owners = new ArrayList<>(); @Override protected Product createProduct(String owner) { return new IDCard(owner); } @Override protected void registerProduct(Product p) { owners.add(((IDCard) p).getOwner()); } }
Main
This class is used to run tests
public class Main { public static void main(String[] args) { Factory factory = new IDCardFactory(); Product card1 = factory.create("张三"); Product card2 = factory.create("李四"); Product card3 = factory.create("王五"); card1.use(); card2.use(); card3.use(); } }