您的位置:首页 > 其它

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

2016-08-05 18:20 671 查看

定义

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

适用场景

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

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

优点

容易扩展

便于维护

比较灵活

类图



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




本文代码可在github查看:点击此处
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息