---
title: "设计模式之模板模式"
author: "西子湖畔的家"
date: "2016-03-11T20:29:45Z"
tags: ["模板模式"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2016-03-11T20:29:45Z"
id: 2282296
url: "https://wgfhit.iteye.com/blog/2282296"
---

模板模式，字面意思针对的是在应用开发中流程固定，具有固定模板的解决方法。

        举例，在应用中流程分为before、onbusiness、end三个步骤，其中，before和end是固定不变的，而onBusiness根据具体的用户不同而不同。这个时候，就应用模板模式。代码如下：

       模板的代码为：

```
package com.designpattern.template;

abstract public class Template{

    public void template(){

        before();
        onBusiness();
        end();
    }

    public void before(){
        System.out.println("before");
    }

    abstract public void onBusiness();

    public void end(){
        System.out.println("end");
    }
}
```

 其他的需要这个模板的可以继承这个模板类，并添加具体的onBussiness方法。代码如下：

```
package com.designpattern.template;

public class ActualExecutor extends Template{


    @Override
    public void onBusiness(){
        System.out.println("on business.");
    }

}
```

 这样，ActualExecutor类继承了Template类中的before和end方法。

测试代码如下：

```
package com.designpattern.template;

import org.junit.Test;

public class TemplateTest{

    @Test
    public void testTemplate(){

        ActualExecutor actualExecutor = new ActualExecutor();
        actualExecutor.template();
    }
}
```

 结果为：

```
before
on business.
end

Process finished with exit code 0
```

 简单实现了模板模式。