concept

Provides an interface for creating a set of related or interdependent objects without specifying their concrete classes. The difference from the previous factory method pattern is that there are multiple abstract factories, and each concrete factory can create multiple products. The advantage is to separate the interface from the implementation and let the client program toward the interface. Disadvantages are too many factories to be cautious; It is also not good to extend the product because adding a product requires modifying the abstract factory.

Usage scenarios

A group of products has the same series of parts, but there are many differences in the types of the same parts (such as large, medium, small, etc.)

implementation

  • Factory Abstract Factory: Declares A set of methods for creating each product (e.g., A, B)
  • Factory1 Factory2 Concrete Factory: Produces A set of specific products that make up A product category (e.g. Factory1 produces small A and small B, Factory produces large A and large B)
  • ProductA ProductB Abstract product
  • ProductA1 ProductA2 ProductB1 ProductB2
public abstract class ProductA{ } public abstract class ProductB{ } public class ProductA1 extends ProductA { } public class ProductA2 extends ProductA { } public class ProductB1 extends ProductB { } public class ProductB2 extends ProductB  { } public abstract class Factory{ public abstract ProductA createProductA(); public abstract ProductB createProductB(); } public class Factory1 extends Factory{ public ProductAcreateProductA() {return new ProductA1();
    }
    public ProductB createProductB() {return new ProductB1();
    }
}

public class Factory2 extends Factory{
   public ProductA createProductA() {return new ProductA2();
    }
    public ProductB createProductB() {returnnew ProductB2(); }}Copy the code