设计模式中的访问者模式(Visitor Pattern)是一种行为型设计模式,它允许我们在不修改对象结构的情况下添加新的操作到对象中。这种模式通常用于处理一组对象结构,并且希望对这些对象执行一些操作,但又不希望改变这些对象的结构。

基本概念

访问者模式包含以下主要角色:

  • Subject(主题):定义一个接口,用于接收访问者对象。
  • ConcreteSubject(具体主题):实现Subject接口,定义接受访问者的具体操作。
  • Visitor(访问者):定义访问者的操作,它包含一个对Subject类集合的引用。
  • ConcreteVisitor(具体访问者):实现Visitor接口,定义对每个具体Subject类的访问操作。

使用场景

  • 当一个对象结构包含很多类,并且它们之间相互独立,且需要添加新的操作时。
  • 当需要遍历一个对象结构中的各个元素,并执行一些操作时。
  • 当需要避免使用继承,从而实现算法的动态添加。

例子

假设我们有一个图形编辑器,它包含多种图形元素,如圆形、矩形等。我们希望为这些图形元素添加一个计算面积的操作。

interface Shape {
    double area();
}

class Circle implements Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double area() {
        return Math.PI * radius * radius;
    }
}

class Rectangle implements Shape {
    private double width;
    private double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public double area() {
        return width * height;
    }
}

class ShapeVisitor {
    public void visit(Circle circle) {
        System.out.println("Circle area: " + circle.area());
    }

    public void visit(Rectangle rectangle) {
        System.out.println("Rectangle area: " + rectangle.area());
    }
}

class Application {
    public static void main(String[] args) {
        Shape circle = new Circle(5);
        Shape rectangle = new Rectangle(4, 6);

        ShapeVisitor visitor = new ShapeVisitor();
        visitor.visit(circle);
        visitor.visit(rectangle);
    }
}

以上代码演示了如何使用访问者模式计算圆形和矩形的面积。

扩展阅读

更多关于设计模式的信息,请访问本站设计模式专栏

Shape Pattern