访问者设计模式

访问者设计模式:
##被访问者:
有一些稳定的结构对象,提供accept方法供访问者进行访问

##访问者:
一些访问者,有一个visitor方法实现对对象的访问,不同的对象会做出不同的反应!

##应用
公司年终奖考核:
被访问者有:程序员,产品经理(accept(Visitor))
访问者:CEO,CTO(visit(…))
CEO可能只会关注KPI,CTO可能只会关注程序员的KPI+代码量,产品经理的KPI+产品数量
不同访问对象对被访问对象的访问可能产生不同的结果!

##实现

`
public interface Visitor {

void visit(Manager manager);
void visit(Engineer engineer);

}

public class CEOVisitor implements Visitor {
@Override
public void visit(Manager manager) {
System.out.println("manager kpi “+manager.getKpi()+” products "+manager.getProducts());
}

@Override
public void visit(Engineer engineer) {
    System.out.println("engineer kpi "+engineer.getKpi());
}

}

public class CTOVisitor implements Visitor {
@Override
public void visit(Manager manager) {
System.out.println("manager kpi “+manager.getKpi()+” products "+manager.getProducts());
}

@Override
public void visit(Engineer engineer) {
    System.out.println(" engineer kpi "+engineer.getKpi()+"  products "+engineer.getCodeLine());
}

}

public abstract class Staff {

private String kpi;

public String getKpi() {
    return kpi;
}

public void setKpi(String kpi) {
    this.kpi = kpi;
}

protected abstract void accept(Visitor visitor);

}

public class Engineer extends Staff {

public Engineer() {
    setKpi("1.0");
}



public int getCodeLine() {
    return new Random(100).nextInt();
}

@Override
protected void accept(Visitor visitor) {
    visitor.visit(this);
}

}

public class Manager extends Staff {

public Manager() {
    setKpi("3.0");
}



public int getProducts() {
    return new Random(1000).nextInt();
}

@Override
protected void accept(Visitor visitor) {
    visitor.visit(this);
}

}

public class BusinessReport {
private Visitor visitor;
private List staffList = new ArrayList<>();
public BusinessReport() {
staffList.add(new Engineer());
staffList.add(new Engineer());
staffList.add(new Manager());
staffList.add(new Manager());
}

public void showReport(Visitor visitor) {
    this.visitor = visitor;
    visitAll();
}
public void visitAll() {
    for (Staff staff:staffList) {
        staff.accept(visitor);
    }
}

public class Test {

public static void main(String[] args) {
    BusinessReport businessReport = new BusinessReport();
    System.out.println("CEO-------------------");
    CEOVisitor ceoVisitor = new CEOVisitor();
    businessReport.showReport(ceoVisitor);
    System.out.println("CEO-------------------");

    System.out.println("CTO-------------------");
    CTOVisitor ctoVisitor = new CTOVisitor();
    businessReport.showReport(ctoVisitor);
    System.out.println("CTO-------------------");
}

}

`

##类结构图

访问者设计模式_第1张图片

你可能感兴趣的:(设计模式)