Abstract Factory pattern

define

In the factory method, the horse factory can only produce horses and the duck factory can only produce ducks. But it shows that in life the farm can raise not only animals but also plants and therefore the abstract factory model has to consider the production of multi-grade products

To use an abstract factory, the following conditions need to be met:

  • There are multiple product families, and each specific factory creates the same family but different grades of products
  • Family products can be used together

Pattern structure and implementation

structure

  • Abstract factory: Provides an interface to multiple products, contains creation methods for multiple products, and can create multiple different levels of products
  • Concrete factory: Multiple abstract methods that implement abstract factories to create concrete products
  • Abstract product
  • Specific products

implementation

package AbstractFactory; /** * @author Richard * @date 23 November 2021 15:48:00 * @description TODO */ public class FarmTest {public static void main(String[] args) { Farm sh=new SHFarm(); Duck duck= (Duck) sh.newAnimal(); duck.shout(); Fruit tomoto= (Fruit) sh.newPlant(); tomoto.show(); }} /** ** public void shout(); } public void show(); /** * implements Animal {@override public void shout() {system.out.println (" implements Animal "); @override public void shout() {system.out.println (" implements Animal "); } /** * implements Plant{@override public void show() {system.out.println (" implements Plant "); {@override public void show() {system.out.println (" vegetables are ready to eat "); } /** * interface Farm{public Animal newAnimal(); public Plant newPlant(); } /** * implements Farm {@override public Animal newAnimal() {system.out.println (" 动 物 动 物 "); return new Duck(); } @override public Plant newPlant() {system.out.println (" fruit can eat "); return new Fruit(); */ class NMGFarm implements Farm{@override public Animal newAnimal() {system.out.println (" horse born "); return new Horse(); } @override public Plant newPlant() {system.out.println (" vegetables can eat "); return new Vegetable(); }}Copy the code