访问者模式的一个小例子

用junit来测试代码

555

public class fwzTest {
    @Test
    public void Test1(){
        VistorBei girl = new Girl();
        VistorBei guy = new Guy();
        China china = new China();
        china.add(girl);
        china.add(guy);
        Vistor enemy = new Enemy();
        Vistor friend = new Friend();
        china.accept(enemy);
        china.accept(friend);
    }
}
public class China {
    private List<VistorBei> vb = new ArrayList<>();
    public void add(VistorBei vistorBei){
        vb.add(vistorBei);
    }
    public void accept(Vistor vistor){
        for (Object o : vb) {
            ((VistorBei) o).accept(vistor);
        }
    }
}
public interface Vistor {
    void visitGril(Girl girl);
    void visitGuy(Guy guy);
}
public interface VistorBei {
    void accept(Vistor v);
}
public class Friend implements Vistor{

    @Override
    public void visitGril(Girl girl) {
        girl.dance();
    }

    @Override
    public void visitGuy(Guy guy) {
        guy.handshake();
    }
}
public class Enemy implements Vistor{
    @Override
    public void visitGril(Girl girl) {
        girl.kill();
    }

    @Override
    public void visitGuy(Guy guy) {
        guy.kill();
    }
}

public class Girl implements VistorBei{

    @Override
    public void accept(Vistor v) {
        v.visitGril(this);
    }

    public void dance(){
        System.out.println("跳舞~");
    }

    public void kill(){
        System.out.println("砍你~");
    }
}
public class Guy implements VistorBei{
    @Override
    public void accept(Vistor v) {
        v.visitGuy(this);
    }

    public void handshake(){
        System.out.println("握手~");
    }

    public void kill(){
        System.out.println("拿烟头烫你~");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值