设计模式之模板方法

跟策略方法类似,就是换方法

public class App {
    public static void main(String[] args) {
        HalflingThief thief=new HalflingThief(new HitAndRunMethod());
        thief.steal();
        thief.changeMethod(new SubtleMethod());
        thief.steal();
    }
}
public class HalflingThief {
    private StealingMethod method;
    public HalflingThief(StealingMethod method){
        this.method=method;
    }
    public void steal(){
        method.steal();
    }
    public void changeMethod(StealingMethod method){
        this.method=method;
    }
}
public class HitAndRunMethod extends StealingMethod{

    @Override
    protected String pickTarget() {
        return "old goblin woman";
    }

    @Override
    protected void confuseTarget(String target) {
        System.out.println("Approch the "+target+" from behind");
    }

    @Override
    protected void stealTheItem(String target) {
        System.out.println("Grab the handbag and run away fast");
    }
}
public abstract class StealingMethod {
    protected abstract String pickTarget();
    protected abstract void confuseTarget(String target);
    protected abstract void stealTheItem(String target);

    public void steal(){
        String target=pickTarget();
        System.out.println("The target has been chosen as "+target);
        confuseTarget(target);
        stealTheItem(target);
    }
}
public class SubtleMethod extends StealingMethod {
    @Override
    protected String pickTarget() {
        return "shop keeper";
    }

    @Override
    protected void confuseTarget(String target) {
        System.out.println("Approcch the "+target+" with tears running and hug him!");
    }

    @Override
    protected void stealTheItem(String target) {
        System.out.println("While in close contact grab the "+target+"'s wallet");
    }
}

当替换整个方法时,就是换了个模板

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值