北辰

c/c++/java程序

java设计模式进阶_template-method

这里写图片描述

//
//
//  Generated by StarUML(tm) Java Add-In
//
//  @ Project : Untitled
//  @ File Name : StealingMethod.java
//  @ Date : 2016/8/30
//  @ Author : 
//
//




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


//
//
//  Generated by StarUML(tm) Java Add-In
//
//  @ Project : Untitled
//  @ File Name : SubtleMethod.java
//  @ Date : 2016/8/30
//  @ Author : 
//
//




public class SubtleMethod extends StealingMethod {
    protected String pickTarget() {
        return "shop keeper";
    }

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

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

//
//
//  Generated by StarUML(tm) Java Add-In
//
//  @ Project : Untitled
//  @ File Name : HalflingThief.java
//  @ Date : 2016/8/30
//  @ Author : 
//
//




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

//
//
//  Generated by StarUML(tm) Java Add-In
//
//  @ Project : Untitled
//  @ File Name : HitAndRunMethod.java
//  @ Date : 2016/8/30
//  @ Author : 
//
//




public class HitAndRunMethod extends StealingMethod {
    protected String pickTarget() {
        return "old goblin woman";
    }

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

    protected void stealTheItem(String target) {
        System.out.println("Grab the handbag and run away fast!");
    }
}

/**
 * 一个算法的模板方法定义了一个框架。算法提供实现子类的空白部分。
 * 在这个例子中HalflingThief包含StealingMethod,可以改变。
 * 第一个小偷与SubtleMethod HitAndRunMethod然后。
 *
 */
public class App {

    public static void main(String[] args) {
        HalflingThief thief = new HalflingThief(new HitAndRunMethod());
        thief.steal();
        thief.changeMethod(new SubtleMethod());
        thief.steal();
    }

}







阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wwww_com/article/details/52367181
文章标签: java设计模式
个人分类: java设计模式进阶
上一篇java设计模式进阶_iterator
下一篇java设计模式进阶_memento
想对作者说点什么? 我来说一句

Java23种设计模式讲解

2018年03月09日 2.04MB 下载

没有更多推荐了,返回首页

关闭
关闭