1. What is the abstract factory pattern?
The abstract factory pattern provides the best way to create objects. In the abstract factory pattern, abstract methods are responsible for creating a factory of related objects, without the need to explicitly specify their classes.
2. Usage scenarios
3. How to implement
4. Advantages When adding a product, you only need to create a product object and the factory class of the product.
6. Application examples and UML
The abstract factory pattern provides the best way to create objects. In the abstract factory pattern, abstract methods are responsible for creating a factory of related objects, without the need to explicitly specify their classes.
2. Usage scenarios
Similar to factory pattern
3. How to implement
Provide an abstract class responsible for creating related objects, which are implemented in subclasses.
4. Advantages When adding a product, you only need to create a product object and the factory class of the product.
5. Disadvantages
。。
。
6. Application examples and UML
Code example:
Create a variety of geometric shapes, circles, rectangles, squares
UML:
7. Code implementation
7.1 Abstract class AbstractShapeFactory
public abstract class AbstractShapeFactory { public abstract Shape getShape(); }
7.2 Circle Factory Class CircleFactory
public class CircleFactory extends AbstractShapeFactory{ @Override public Shape getShape() { return new Circle(); } }
7.3 Rectangle Factory Class RectangleFactory
public class RectangleFactory extends AbstractShapeFactory{ @Override public Shape getShape() { return new Rectangle(); } }7.4 Square Factory Class SquareFactory
public class SquareFactory extends AbstractShapeFactory{ @Override public Shape getShape() { return new Square(); } }
8. Test class
8.1 Test class
public class AbstractFactoryTest { @Test public void test(){ CircleFactory circleFactory = new CircleFactory(); Shape circle = circleFactory.getShape(); circle.draw(); RectangleFactory rectangleFactory = new RectangleFactory(); Shape rectangle = rectangleFactory.getShape(); rectangle.draw(); SquareFactory squareFactory = new SquareFactory(); Shape square = squareFactory.getShape(); square.draw(); } }
8.2 Test Results
this is Circle drawing this is Rectangle drawing this is Square drawing