The factory method pattern is a creational design pattern. It defines the process of creating objects through an interface, and delegates the specific creation process to a specific factory class that implements the interface, thus decoupling the creation process and specific classes, making it easy to expand and improve. Testability. The main structures include abstract factory, concrete factory and product.
Java Design Pattern Factory Method Pattern Revealed
Introduction
Factory Method A pattern is a creational design pattern that allows programmers to define an interface for creating objects but abstracts the creation process. This means that the process of concrete object creation can be handled by a concrete factory subclass that implements this interface.
Advantages of the factory method pattern
Structure
The factory method pattern mainly consists of three parts:
Code Example
The following is a Java code example of the factory method pattern:
// 抽象工厂接口 interface ShapeFactory { Shape createShape(ShapeType type); } // 具体工厂类 class CircleFactory implements ShapeFactory { @Override public Shape createShape(ShapeType type) { return new Circle(); } } // 具体工厂类 class SquareFactory implements ShapeFactory { @Override public Shape createShape(ShapeType type) { return new Square(); } } // 产品类 class Shape { private String type; public Shape(String type) { this.type = type; } public String getType() { return type; } } // 圆形产品类 class Circle extends Shape { public Circle() { super("Circle"); } } // 正方形产品类 class Square extends Shape { public Square() { super("Square"); } } // 客户端代码 public class Main { public static void main(String[] args) { ShapeFactory circleFactory = new CircleFactory(); Shape circle = circleFactory.createShape(ShapeType.CIRCLE); System.out.println(circle.getType()); // 输出: Circle ShapeFactory squareFactory = new SquareFactory(); Shape square = squareFactory.createShape(ShapeType.SQUARE); System.out.println(square.getType()); // 输出: Square } }
Conclusion
The factory method pattern is a flexible and extensible design pattern that provides a way to decouple the creation process from concrete classes. This makes the code easier to maintain and extend, and improves testability.
The above is the detailed content of Java Design Patterns Factory Method Pattern Revealed. For more information, please follow other related articles on the PHP Chinese website!