public interface Visitor {
void visit(CPU cpu);
void visit(EarPhone earPhone);
}
public class GeneralVisitor implements Visitor{
@Override
public void visit(CPU cpu) {
System.out.println("CPU名称:"+cpu.getModelName());
}
@Override
public void visit(EarPhone earPhone) {
System.out.println("耳机名称:"+earPhone.getInterfaceName());
}
}
public class ProVisitor implements Visitor{
@Override
public void visit(CPU cpu) {
System.out.println("CPU:"+cpu.getModelName()+" "+cpu.getHz());
}
@Override
public void visit(EarPhone earPhone) {
System.out.println("耳机:"+earPhone.getInterfaceName()+" "+earPhone.getPrice());
}
}
public interface Component {
void accept(Visitor visitor);
}
public class CPU implements Component {
private int hz;
private String modelName;
public int getHz() {
return hz;
}
public void setHz(int hz) {
this.hz = hz;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
public class EarPhone implements Component {
private String interfaceName;
private int price;
public String getInterfaceName() {
return interfaceName;
}
public void setInterfaceName(String interfaceName) {
this.interfaceName = interfaceName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
public class Phone implements Component {
private List<Component> components;
public List<Component> getComponents() {
return components;
}
public void setComponents(List<Component> components) {
this.components = components;
}
public void accept(Visitor visitor) {
for(Component component:components){
component.accept(visitor);
}
}
}