设计模式开始--访问者模式

访问者模式

一、作用

(1)访问者模式适用于数据结构相对稳定的系统,把处理从数据结构中分离出来,当系统有比较稳定的数据结构,又有易于变化的算法,访问者模式是比较适用的。

(2)目的是封装施加于某种数据结构元素之上的操作,且可以在不修改原有的系统的基础上增加新的操作方式。

 二、类图

三、实现

(1)IShape定义目前的操作需求和要接纳的Visitor

public interface IShape {
    public float getArea();
    public Object accept(IVisitor visitor);
}
public class Triangle implements IShape {
    float x1,y1,x2,y2,x3,y3;
    public Triangle(float x1,float y1,float x2,float y2, float x3,float y3)
    {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
        this.x3 = x3;
        this.y3 = y3;
    }
    public float getDist(float u1, float v1, float u2, float v2)
    {
        return (float)Math.sqrt((u1-u2)*(u1-u2) + (v1-v2)*(v1-v2));
    }
    @Override
    public float getArea() {
        float a = getDist(x1,y1,x2,y2);
        float b = getDist(x1,y1,x3,y3);
        float c = getDist(x3,y3,x2,y2);
        float s = (a+b+c)/2;
        return (float)Math.sqrt(s*(s-a)*(s-b)*(s-c));
    }
    @Override
    public Object accept(IVisitor visitor) {
        return visitor.visitor(this);
    }
}
View Code

(2)IVisitor定义要接纳的对象和接纳对象后实现的新功能

public interface IVisitor {
    Object visitor(Triangle t);
}
public class LengthVisitor implements IVisitor {
    @Override
    public Object visitor(Triangle t) {
        float a = t.getDist(t.x1,t.y1,t.x2,t.y2);
        float b = t.getDist(t.x1,t.y1,t.x3,t.y3);
        float c = t.getDist(t.x3,t.y3,t.x2,t.y2);
        return a+b+c;
    }
}
View Code

(3)Client客户测试类

public class Client {
    public static void main(String[] args) {
        IVisitor visitor = new LengthVisitor();
        Triangle shape = new Triangle(0,0,2,0,0,2);
        shape.accept(visitor);
        System.out.println(shape.getArea());
        System.out.println(visitor.visitor(shape));
    }
}
View Code
原文地址:https://www.cnblogs.com/sunshisonghit/p/4389105.html