This article was compiled by Colodoo (Paper Umbrella) from the reference book graphic Design Patterns

QQ 425343603 Java Learning Exchange Group (717726984)

The factory pattern

  • Product (Product)
  • Creator
  • ConcreteProducts
  • ConcreteCreator

Product (Product)

The Product role belongs to the framework side and is an abstract class.

Creator

On the framework side, the Creator role is the abstract class responsible for generating the Product role, but the specific processing is determined by the subclass ConcreteCreator role.

ConcreteProducts

The ConcreteProduct role belongs to the concrete processing side. It decides the concrete products.

ConcreteCreator (ConcreteCreator)

The ConcreteCreator role belongs to the concrete processing side and is responsible for generating concrete products.

The class diagram

Code sample

/** * factory abstract class **@authorColodoo (paper umbrella) **/
public abstract class Factory {
    
    / / create
    public final Product create(String owner) {
        Product product = new createProduct(owner);
        registerProduct(product);
        return product;
    }
    
    // Create a product
    protected abstract Product createProduct(String owner);
    
    // Register the product
    protected abstract void registerProduct(Product product);
    
}
Copy the code
/** * Specific factory class **@authorColodoo (paper umbrella) **/
public class ConcreteFactory extends Factory {
    
    private List owners = new ArrayList();
    
    // Create a product
    protected Product createProduct(String owner) {
        return new ConcreteProduct(owner);
    }
    
    // Register the product
    protected void registerProduct(Product product) {
        owners.add(((ConcretedProduct) product).getOnwer());
    }
    
    // Get the owner list
    public List getOwners(a) {
        returnowners; }}Copy the code
/** * Product abstraction class **@authorColodoo (paper umbrella) **/
public abstract class Product {
    
    / / use
    public abstract void use(a);
    
}
Copy the code
/** * Specific product category **@authorColodoo (paper umbrella) **/
public class ConcreteProduct extends Product {
    
    / / owner
    private String owner;
    
    // constructor
    public ConcreteProduct(String owner) {
        this.owner = owner;
    }
    
    // Get the owner
    public String getOwner(a) {
        return this.owner;
    }
    
    / / use
    public void use(a) {
        // Process logic
        // TODO
        System.out.println("Use product"); }}Copy the code
public class Main {
    
    public static void main(String[] args) {
        
        Factory factory = new ConcreteFactory();
        Product prodcut1 = factory.create("1");
        Product prodcut2 = factory.create("2"); prodcut1.use(); prodcut2.use(); }}Copy the code