Java - 模板方法模式

-- 模板方法模式(Template Method) ,最简单的模式之一,把具有特定的步骤算法中的某些必要的处理委让给抽象方法,通过子类继承对抽象方法的不同实现改变整个算法的行为。

简单来说就是定义一个类提供抽象方法,再定义几个子类去实现方法……

一、模式结构

引用官方结构图:

组成(角色) 作用
AbstractClass (抽象父类) 提供抽象方法,并且还有模板方法(调用自身的方法)
ConcreteClass (具体实现子类) 实现抽象方法

二、简易栗子

1、抽象父类

- 提供抽象方法和模板方法(调用自身的方法)

package com.behavior.templateMethod;

/**
 * @description: 抽象车
 * @author: ziHeng
 * @create: 2018-08-14 14:29
 **/
public abstract class AbstractCar {

    //汽车轮廓架构
    public abstract void frame();

    //底部
    public abstract void bottom();

    //轮胎
    public abstract void tire();


    //提供模板方法
    public void templateMethod(){
        //调用自身抽象方法
        this.frame();
        this.bottom();
        this.tire();
    }

}

2、具体实现子类 - 跑车

package com.behavior.templateMethod;

/**
 * @description: 实现类 - 跑车
 * @author: ziHeng
 * @create: 2018-08-14 14:31
 **/
public class SportCar extends AbstractCar {

    @Override
    public void frame() {
        System.out.println("跑车架构");
    }

    @Override
    public void bottom() {
        System.out.println("跑车底部");
    }

    @Override
    public void tire() {
        System.out.println("跑车轮胎");
    }
}

调用Test:

package com.behavior.templateMethod;

/**
 * @description: 模板方法测试
 * @author: ziHeng
 * @create: 2018-08-14 14:25
 **/
public class TemplateMethodTest {

    public static void main(String[] args) {
        AbstractCar sportCar = new SportCar();
        sportCar.templateMethod();
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_39569611/article/details/81666056