设计模式-模板方法

当我们对一类事情处理熟悉之后,通常可以总结形成一定的流程,或者处理这类事情的方法论。往后处理具体类似的事情时,我们使用该方法论进行套用,且做些细微调整即可。

1. 概述

定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。这样可以避免在每个类中写一些相同方法。

1.1. 优点

  • 封装不变部分,扩展可变部分;
  • 提取公共代码,便于维护;
  • 行为由父类控制,子类实现;

1.2. 缺点

  • 每一个不同的实现都需要一个子类来实现,导致类的个数增加,使得系统更加庞大。

1.3. 使用场景

  • 有多个子类共有的方法,且逻辑相同;
  • 重要的、复杂的方法,可以考虑作为模板方法。

2. 代码实例

我们来实现烹饪的业务,定义一般的烹饪有三个步骤:prepare(准备食材)、cooking(烹饪)、plating(摆盘),但是不规定具体实现细节

package com.skystep.设计模式.模板方法;


public abstract class CookingTemp {

    abstract void select();
    abstract void cooking();
    abstract void plating();

    private void prepare() {
        System.out.println("请选择炒的食材");
        select();
        System.out.println("完成食材的选择");
    }


    public final void cook() {
        System.out.println("做菜开始...");
        prepare();
        cooking();
        plating();
        System.out.println("做菜结束...");
    }
}

现在我们来炒上海青,锅热倒油炒10分钟起锅,摆成爱的形状

package com.skystep.设计模式.模板方法;


public class FryShangHaiQing extends CookingTemp {

    @Override
    void select() {
        System.out.println("选择上海青");
    }

    @Override
    void cooking() {
        System.out.println("锅热倒油炒10分钟起锅");
    }

    @Override
    void plating() {
        System.out.println("摆成爱的形状");
    }
}


现在我们也可以蒸一条鲈鱼,水蒸10分钟起锅倒入煎油,摆成鱼的形状

package com.skystep.设计模式.模板方法;


public class SteamedFish extends CookingTemp {

    @Override
    void select() {
        System.out.println("选择鲈鱼");
    }

    @Override
    void cooking() {
        System.out.println("水蒸10分钟起锅倒入煎油");
    }

    @Override
    void plating() {
        System.out.println("摆成鱼的形状");
    }
}


最后实现一个客户端,炒一个上海青、蒸一条鲈鱼试一下


package com.skystep.设计模式.模板方法;


public class Client {
    public static void main(String[] args) {
        CookingTemp cooking = new SteamedFish();
        cooking.cook();

        cooking = new FryShangHaiQing();
        cooking.cook();
    }
}

做菜开始...
请选择炒的食材
选择鲈鱼
完成食材的选择
水蒸10分钟起锅倒入煎油
摆成鱼的形状
做菜结束...

做菜开始...
请选择炒的食材
选择上海青
完成食材的选择
锅热倒油炒10分钟起锅
摆成爱的形状
做菜结束...

Process finished with exit code 0

我们规定了烹饪得所有流程,但是不限制准备什么菜,怎么烹,摆成什么样子;但是有些通用的业务我们可以在抽象类中准备好,如打印部分的代码,可以替换成实际业务代码。

3. 扩展解读

3.1. 线程的创建


public class Client {
    public static void main(String[] args) {
        Thread thread = new Thread(()->System.out.println("创建线程"));
        thread.start();
    }
}

在上面的例子中,我们创建线程时,实现了线程的具体业务,打印了"创建线程",其实,Thread 底层使用了模板方法设计模式,其模板方法是 start,当调用了 start 函数,系统调用了 start0 方法,start0 是本地方法,本地方法执行回调对应的 run 方法。


package java.lang;

public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}


/**
     * Causes this thread to begin execution; the Java Virtual Machine
     * calls the <code>run</code> method of this thread.
     * <p>
     * The result is that two threads are running concurrently: the
     * current thread (which returns from the call to the
     * <code>start</code> method) and the other thread (which executes its
     * <code>run</code> method).
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.
     *
     * @exception  IllegalThreadStateException  if the thread was already
     *               started.
     * @see        #run()
     * @see        #stop()
     */
    public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

    private native void start0();

    /**
     * If this thread was constructed using a separate
     * <code>Runnable</code> run object, then that
     * <code>Runnable</code> object's <code>run</code> method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of <code>Thread</code> should override this method.
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

posted @ 2021-10-26 16:25  yaomianwei  阅读(6)  评论(0)    收藏  举报