程序员

设计模式——模板方法模式

2018-01-10  本文已影响0人  BrightLoong
template

模板方法属于行为型模式

一. 简介

模板方法模式:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤

准备一个抽象类,将部分逻辑以具体方法以及具体构造函数的形式实现,然后声明一些抽象方法来迫使子类实现剩余的逻辑。不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑有不同的实现。这就是模板方法模式的用意。

模板方法模式是基于集成的代码复用的模式。

二. UML类图

UML图

三. 代码实现

1. AbstractTemplate抽象模板类

package brightloong.github.io.template;

public abstract class AbstractTemplate {
    public void templateMehtod() {
        System.out.println("开始连接,连接成功...");
        abstracMethod();
        System.out.println("断开连接,释放资源...");
    }
    
    protected abstract void abstracMethod();
}

2. concreteTemplate1抽象模板类具体实现1

package brightloong.github.io.template;

public class ConcreteTemplate1 extends AbstractTemplate{

    /** (non-Javadoc)
     * @see brightloong.github.io.template.AbstractTemplate#abstracMethod()
     */
    @Override
    public void abstracMethod() {
        System.out.println("查询用户表....");
    }

}

3. concreteTemplate2抽象模板类具体实现2

package brightloong.github.io.template;

public class ConcreteTemplate2 extends AbstractTemplate{

    /** (non-Javadoc)
     * @see brightloong.github.io.template.AbstractTemplate#abstracMethod()
     */
    @Override
    public void abstracMethod() {
        System.out.println("查询商品表...");
    }

}

4. Client客户端调用测试代码和结果

package brightloong.github.io.template;

public class Client {
    public static void main(String[] args) {
        AbstractTemplate template = new ConcreteTemplate1();
        template.templateMehtod();
        System.out.println("");
        AbstractTemplate template2 = new ConcreteTemplate2();
        template2.templateMehtod();
    }
}

运行结果如下:

开始连接,连接成功...
查询用户表....
断开连接,释放资源...

开始连接,连接成功...
查询商品表...
断开连接,释放资源...

四. 使用场景

五. 优缺点

1. 优点

2. 缺点

上一篇 下一篇

猜你喜欢

热点阅读