Java设计模式之工厂方法模式揭秘

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

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设计模式之工厂方法模式揭秘的详细内容,更多请关注小编网其它相关文章!

转载请说明出处 内容投诉内容投诉
南趣百科 » Java设计模式之工厂方法模式揭秘

南趣百科分享生活经验知识,是您实用的生活科普指南。

查看演示 官网购买