When the system is ready to provide users with a series of related objects, but does not want user code to be coupled to these objects, the abstract factory pattern can be used.
1) Abstract product--Car
2) Specific product--BYDCar, TSLCar
3) Abstract factory Factory
4) Specific factory--BYDFactory, TSLFactory
/** * 抽象产品 */ public abstract class Car { public abstract String getName(); }
/** * 具体产品 */ public class BYDCar extends Car { String name; public BYDCar(String name){ this.name = name; } @Override public String getName() { return name; } }
/** * 抽象工厂 */ public abstract class CarFactoty { public abstract Car createCar(String name); }
/** * 具体工厂 */ public class BYDFactory extends CarFactoty { @Override public BYDCar createCar(String name) { return new BYDCar(name); } }
1) The abstract factory pattern can create a Series-related objects decouple users from objects of these classes
2) Using the abstract factory pattern can conveniently configure a series of objects for users.
3) In the abstract factory pattern, you can add a "concrete factory" at any time to provide users with a set of related objects.
For example: In the above example, if the user needs a Tesla car, it can be completed by creating a Tesla object and a Tesla factory.
/** * 具体产品 */ public class TSLCar extends Car { String name; public TSLCar(String name){ this.name = name; } @Override public String getName() { return name; } }rrree
The above is the detailed content of How to implement the abstract factory pattern of Java design patterns. For more information, please follow other related articles on the PHP Chinese website!