1:概述
小威哥今天为大家带来的是另外一种非常简单又无比实用的设计模式
其实在之前的 代理模式 中我也提到过了模板模式,其实和静态代理基本没啥区别。
2:netty中的模板模式
其实如果有玩过netty的同学应该都知道,netty的handler就是用了模板模式去做责任链的处理。
netty的SimpleChannelInboundHandler.class
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
boolean release = true;
try {
if (this.acceptInboundMessage(msg)) {
//这里实现我们的自己的处理逻辑
this.channelRead0(ctx, msg);
} else {
release = false;
ctx.fireChannelRead(msg);
}
} finally {
if (this.autoRelease && release) {
ReferenceCountUtil.release(msg);
}
}
}
//这个眼熟吧?就是我们经常重写的处理逻辑
protected abstract void channelRead0(ChannelHandlerContext var1, I var2) throws Exception;
netty的handler组件就定义了一个抽象的模板类,让我们去实现我们自己的功能,其实本质上也是对一个方法进行代理增强,本质上和代理模式并没有什么区别。
3:模板模式
下面我们就来自己动手实现一个模板模式
//定义一个模板类
public abstract class HouseTemplate {
protected HouseTemplate(String name){
this.name = name;
}
protected String name;
abstract void buildWay();
public final void buildHouse(){
System.out.println("买建房子的材料完成");
buildWay();
System.out.println("房子建造完成");
}
}
//写一个具体实现方法
public class RealHouseBuild extends HouseTemplate {
public RealHouseBuild(String name) {
super(name);
}
@Override
protected void buildWay() {
System.out.println("开始建造房子");
}
}
//测试执行一下
public static void main(String[] args) {
HouseTemplate houseTemplate = new RealHouseBuild("xxx");
houseTemplate.buildHouse();
}
怎么样,简单吧!
4:总结
设计模式的初衷就是要简洁明了,实用,模板模式就很好的贯彻了这一理念!值得强力推荐,希望大家以后在实际工作中多多使用。