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


    访问者模式

    一、作用

    (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
  • 相关阅读:
    CentOS 7基于Containerd部署Kubernetes v1.20.5
    【k8s记录】二进制安装kubernetes高可用集群全过程完整版v1.20
    前台后台$.psot交互
    $.ajax与$.post、$.get的一点区别
    layui与jQuery一起使用
    用Emmet写前端代码
    栅格布局的实现过程,容器到列的划分
    bootstrap环境
    2个爬虫
    think PHP5中,模板、控制器、JavaScript的url跳转重定向方法
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4389105.html
Copyright © 2020-2023  润新知