The abstract factory pattern is used to create a series of related or interdependent objects without specifying specific classes. Like factory mode, it includes the following roles:
- Factory: abstract factory, declaring factory method, which returns an object of type Product
- ConcreteFactory: implementation of factory, overriding factory method and returning ConcreteProduct instance
- Product: abstract product produced by the factory
- Concrete product: specific product
Consider the following scenario: KFC sells two packages, one economic model including chicken wings and coke, the other high-end model including chicken legs and coffee. It is used to indicate the name of the package needed to get the corresponding food. In this case, the factory mode is no longer applicable. Because factory mode is only responsible for the production of independent products in each sub factory, it is not applicable to create a "product package" at a time, and abstract factory mode is improved in this respect:
//Product family 1: KFC food abstract class KFCFood { public abstract void show(); } class Chicken extends KFCFood { public void show() { System.out.println("Drumsticks+1"); } } class Wings extends KFCFood { public void show() { System.out.println("Chicken wings+1"); } } //Product family 2: KFC beverage abstract class KFCDrink { public abstract void show(); } class Cola extends KFCDrink { public void show() { System.out.println("cola+1"); } } class Coffee extends KFCDrink { public void show() { System.out.println("Coffee+1"); } } //Abstract factory, production package interface IKFCFactory { KFCFood createFood(); KFCDrink createDrink(); } //Economy package, including wings and coke class CheapPackageFactory implements IKFCFactory { public KFCFood createFood() { return new Wings(); } public KFCDrink createDrink() { return new Cola(); } } //Premium package, including drumsticks and coffee class DearPackageFactory implements IKFCFactory { public KFCFood createFood() { return new Chicken(); } public KFCDrink createDrink() { return new Coffee(); } } public class Client { public static void main(String[] args) { //Economy package IFactory factory = new CheapPackageFactory(); KFCFood food1 = factory.createFood(); KFCDrink drink1 = factory.createDrink(); food1.show(); drink1.show(); } }
The abstract factory pattern can be used in the following situations:
- Products of the same product family are used together, and they are interdependent and inseparable
- You only want to provide a set of objects without displaying their implementation process, only their interfaces
- The system does not depend on some specific product classes