天天看點

讀設計模式之禅--通路者模式

  • 定義:封裝一些作用于某種資料結構中的各元素的操作,它可以在不改變資料結構的前提下定義作用于這些元素的新的操作。
package design.visitor;

/**
 * @Author: hyh
 * @Date: 2021/8/27 15:10
 **/
public abstract class Employee {


    private String name;
    private String sex;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public abstract void accept(IVisitor visitor);
}
class CommonEmployee extends Employee{

   private  String job;

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }
    public void job(){
        System.out.println("我的工作是" + this.job);
    }

    @Override
    public void accept(IVisitor visitor) {
        visitor.voist(this);
    }
}
class Manager extends Employee{

    private String report;

    public String getReport() {
        return report;
    }

    public void setReport(String report) {
        this.report = report;
    }

    public void report(){
        System.out.println("本季度報表情況" + this.report);
    }

    @Override
    public void accept(IVisitor visitor) {
        visitor.voist(this);
    }
}
// 抽象一個通路者接口
interface IVisitor{

    void voist(Manager manager);
    void voist(CommonEmployee common);

}
class Vistor implements IVisitor{


    @Override
    public void voist(Manager manager) {
        this.getManageInfo(manager);
    }

    @Override
    public void voist(CommonEmployee common) {
        this.getCommonEmployeeInfo(common);
    }

    public void getCommonInfo(Employee e){
        System.out.println("員工姓名:"+ e.getName());
        System.out.println("員工性别:"+ e.getSex());
    }

    public void getManageInfo(Manager manager){
        this.getCommonInfo(manager);
        manager.report();
    }

    public void getCommonEmployeeInfo(CommonEmployee common){
        this.getCommonInfo(common);
        common.getJob();
    }
}
class Test{
    public static void main(String[] args) {


        CommonEmployee commonEmployee = new CommonEmployee();
        commonEmployee.setJob("開發");
        commonEmployee.setName("張三");
        commonEmployee.setSex("男");


        Manager manager = new Manager();
        manager.setReport("創造營收500億元");
        manager.setName("王經理");
        manager.setSex("女");


        commonEmployee.accept(new Vistor());
        manager.accept(new Vistor());
    }
}
輸出:
員工姓名:張三
員工性别:男
員工姓名:王經理
員工性别:女
本季度報表情況創造營收500億元