设计模式--访问者模式

访问者模式 – 伍六七离开小鸡岛

首先定义国家

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);
        }
    }
}

运行结果

伍六七到了石更国,抓去比肌肉
伍六七到了大礼国,和如花结婚
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值