访问者模式 – 伍六七离开小鸡岛
首先定义国家
public abstract class Country {
private String name;
public Country(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract void accept(IVisitor visitor);
}
石更国
public class HardCountry extends Country {
public HardCountry(String name) {
super(name);
}
@Override
public void accept(IVisitor visitor) {
visitor.visit(this);
}
}
大礼国
public class DaliCountry extends Country {
private String bride;
public DaliCountry(String name) {
super(name);
}
public DaliCountry(String name, String bride) {
super(name);
this.bride = bride;
}
public String getBride() {
return bride;
}
public void setBride(String bride) {
this.bride = bride;
}
@Override
public void accept(IVisitor visitor) {
visitor.visit(this);
}
}
定义访问者
public interface IVisitor {
void visit(HardCountry country);
void visit(DaliCountry daliCountry);
}
伍六七
public class WuLiuqi implements IVisitor {
@Override
public void visit(HardCountry country) {
System.out.println("伍六七到了" + country.getName() + ",抓去比肌肉");
}
@Override
public void visit(DaliCountry country) {
System.out.println("伍六七到了" + country.getName() + ",和" + country.getBride() + "结婚");
}
}
测试类
public class Test {
public static void main(String[] args) {
WuLiuqi wuLiuqi = new WuLiuqi();
List<Country> countryList = new ArrayList<>();
countryList.add(new HardCountry("石更国"));
countryList.add(new DaliCountry("大礼国", "如花"));
for (Country country : countryList) {
country.accept(wuLiuqi);
}
}
}
运行结果
伍六七到了石更国,抓去比肌肉
伍六七到了大礼国,和如花结婚