(14)访问者模式

概念

一个卖车的店铺,车的价格是根据人群决定折扣的,比如学生买车就5折,工人买车就9折。
如果是平时的做法,就会判断是什么人来买车,再决定打多少折扣,这样的设计并不理想,因为有可能下次是自己的亲戚买车,或者其他什么人买车等等,会导致车的这个类频繁修改。

为了解决车这个类频繁修改的问题,可以使用访问者模式。

  • 每个访问者都有车的这个类,比如学生买车,那么学生就是访问者,学生类中存有车的类,学生买车时只要获取到这辆车并拿到车的价格,然后在学生类中根据车的价格处理折扣信息。
  • 当访问者是工人时,就有工人类,在工人类中获取车的价格,并在工人类中处理折扣信息。

实现方式

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * 访问者
 */
public class Demo {
    public static void main(String[] args) {
        // 不同的访问者
        Student student = new Student();
        Worker worker = new Worker();

        // 不同的访问者访问汽车
        Car byd = new Byd("比亚迪", 100000);
        byd.accept(student);
        byd.accept(worker);
    }
}

// 访问者,不同的访问者都要实现该接口
interface Visitor {
    // 折扣。不同的访问者有不同的折扣
    void discount(Byd byd);
}

// 学生
class Student implements Visitor {
    public void discount(Byd byd) {
        System.out.println(String.format(
                "学生买汽车。车名:%s,原价:%s,学生价:%s"
                , byd.getName()
                , byd.getPrice()
                , byd.getPrice() * 0.5));
    }
}

// 工人
class Worker implements Visitor {
    public void discount(Byd byd) {
        System.out.println(String.format(
                "工人买汽车。车名:%s,原价:%s,工人价:%s"
                , byd.getName()
                , byd.getPrice()
                , byd.getPrice() * 0.9));
    }
}

// 汽车,所有汽车都要实现该接口
interface Car {
    void accept(Visitor v);
}

// 比亚迪汽车
@Data
@AllArgsConstructor
class Byd implements Car {
    private String name;
    private Integer price;

    // 添加访问者
    public void accept(Visitor v) {
        v.discount(this);
    }
}

学生买汽车。车名:比亚迪,原价:100000,学生价:50000.0
工人买汽车。车名:比亚迪,原价:100000,工人价:90000.0

posted @ 2021-12-01 10:24  、嘎路的米。  阅读(30)  评论(0)    收藏  举报