工厂方法模式是一种创建型设计模式,它通过接口定义创建对象的流程,将具体创建过程委托给实现该接口的具体工厂类,从而解耦创建过程和具体类,易于扩展和提高可测试性。主要结构包括抽象工厂、具体工厂和产品。

Java 设计模式之工厂方法模式揭秘
引言
工厂方法模式是一种创建型设计模式,它允许程序员定义一个接口用于创建对象,但对创建过程进行了抽象。这意味着具体对象创建的过程可以由实现该接口的具体工厂子类来处理。
立即学习“Java免费学习笔记(深入)”;
工厂方法模式的优点
结构
工厂方法模式主要由三个部分组成:
代码示例
以下是一个工厂方法模式的 Java 代码示例:
// 抽象工厂接口
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
}
}结论
工厂方法模式是一种灵活且可扩展的设计模式,它提供了一种解耦创建过程与具体类的方法。这使得代码更容易维护和扩展,并提高了可测试性。
以上就是Java设计模式之工厂方法模式揭秘的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号