设计模式-行为型-模板方法模式(Template Method Pattern)

来源:互联网 发布:热血三国辅助软件 编辑:程序博客网 时间:2024/05/16 06:15

定义

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

适用场景

       一个复杂的任务,由公司的大神把主要的逻辑写好,然后把比较简单的方法写成抽象的,交给新从同事去开发,相信很多实习的同学都有过这种经历。这种方法适合编程人员水平差距比较明显的公司,比如一个项目组有架构师、高级工程师、初级工程师,可由架构师使用大量的接口、抽象类把系统逻辑串起来,然后按不同的难度分别分给高级工程师和初级工程师

       在程序的主框架相同,细节不同的场合下,可以考虑用模板方法模式;多个子类拥有相同的方法,且这些方法的逻辑相同时,也比较适合使用模板方法模式

优点

  • 容易扩展
  • 便于维护
  • 比较灵活

类图

模板方法模式

package com.vapy.behavior.TemplateMethod;/** *  * @author vapy * */public abstract class AbstractSort {    protected abstract void sort(int[] array, int low, int high);    public final void mainLogic(int[] array){        this.sort(array, 0, array.length -1);        System.out.println("打印结果");        for(int i : array){            System.out.print(i + " ");        }    }}
package com.vapy.behavior.TemplateMethod;/** *  * @author vapy * */public class ConcreteSort extends AbstractSort {    @Override    protected void sort(int[] array, int low, int high) {        {            int l = low;            int h = high;            int povit = array[low];            while (l < h) {                while (l < h && array[h] >= povit) {                    h--;                }                if (l < h) {                    swap(array, h, l);                    l++;                }                while (l < h && array[l] <= povit) {                    l++;                }                if (l < h) {                    swap(array, h, l);                    h--;                }            }            if (l > low) {                sort(array, low, l - 1);            }            if (h < high) {                sort(array, l + 1, high);            }        }    }    private void swap(int[] array, int i, int j) {        array[i] = array[i] ^ array[j];        array[j] = array[i] ^ array[j];        array[i] = array[i] ^ array[j];    }}
package com.vapy.behavior.TemplateMethod;/** *  * @author vapy * */public class Client {    public static void main(String[] args) {        int[] a = {10,28,34,1,35,12,234,5,23};        AbstractSort s = new ConcreteSort();        s.mainLogic(a);    }}

TemplateMethod
本文代码可在github查看:点击此处

5 0
原创粉丝点击