美文网首页
行为型模式-模板方法模式

行为型模式-模板方法模式

作者: 格林哈 | 来源:发表于2020-03-18 22:41 被阅读0次

0 行为型模式

  • 涉及怎样合理地设计对象之间的交互通信
  • 怎样合理的为对象分配职责
  • 让设计富有弹性,易维护,易复用

1 模板方法模式

  • 1.1 描述: 在一个类(大多抽象类)中定义一个算法的骨架,即将若干个方法集中到一个方法中,并称该方法为一个模板方法。模板方法调用的其他方法通常为抽象的方法,这些抽象方法相当于算法骨架的各个步骤,这些步骤的实现可以由子类去完成。

  • 1.2 特点:

    • 模板方法模式是通过把不变行为搬移到超类,去除子类中的重复代码
  • 1.3 场景: 如果多个类中存在某些相似的算法逻辑或者行为逻辑,可以这些相识的逻辑提取到模板方法类中实现,然后让相应的子类根据需要实现某些自定义的逻辑

  • 1.4 案例
    -

    UML
    • 流程:假设开车只有三个步骤
      • 点火
      • 挂挡 有自动挡 手动挡区别,未来可能还有其他区别
      • 运行
  • 代码

package com.mg.springjiemi.templatemethod;
public abstract class Vehicle {
    //模板方法
    public final void  drive(){
        //点火启动汽车
        startTheEngine();
        //挂挡 可能有手动挡,自动挡
        putIntoGear();
        //跑路
        go();
    }
    //开车的步骤
    protected  abstract void putIntoGear();
    //开车的步骤
    public void go(){
        //...
        System.out.println("跑路");
    }
    public void startTheEngine(){
        //...
        System.out.println("开火");
    }

}

package com.mg.springjiemi.templatemethod;
//自动挡汽车
public class VehicleZiDong extends Vehicle {
    @Override
    protected void putIntoGear() {
        System.out.println("挂自动挡");
    }
}

package com.mg.springjiemi.templatemethod;
public class VeicleShouDong extends Vehicle {
    @Override
    protected void putIntoGear() {
        System.out.println("手动挡");
    }
}


2 模板方法与Callback结合使用

  • 2.1 案例
    • 描述:接手一个ice调人脸的服务,ice一些资源操作就跟jdbc操作数据类似,接近30个方法,很多操作都有相似的逻辑
    • Callback接口与模板方法之间的关系看作服务与被服务的关系
      • 模板方法类想要Callback做事,就要提供相应的资源
      • Callback使用提供的资源做事
      • 做完事之后,模板方法类来处理公共的资源,Callback接口不需要关心这些
    • JDBCTemplate 就是这种方式实现,在资源管理上有一个共性,那就是需要在资源使用之后可以安全地释放这些资源。
package com.gerp.service.common;
import com.gerp.common.faceRecognition.FaceRecognitionPrx;
public interface Callback<T> {
    public T callback(FaceRecognitionPrx helloWorld);
}


package com.gerp.service.common;
public class FaceServiceTemplate {
    private final Logger LOGGER = Logger.getLogger(FaceServiceTemplate.class);

    //公共模板
    private <T> T execute(Callback<T> fun) {
        FaceRecognitionPrx helloWorld = null;
        Ice.Communicator ic = null;
        try {
            ic = Ice.Util.initialize();
            Ice.ObjectPrx base = ic.stringToProxy(BaseData.getBaseData().getIce_url());
            helloWorld = FaceRecognitionPrxHelper.checkedCast(base);
            if (helloWorld == null) {
                Error error = new Error("Invalid proxy");
                LOGGER.error(error.getMessage());
                throw error;
            }
            return fun.callback(helloWorld);
        } catch (Ice.LocalException e) {
            LOGGER.error(e.getMessage());
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        } finally {
            if (ic != null) {
                ic.destroy();
            }

        }
        return null;


    }
    /**
     * 2.   人脸检测接口
     *
     * @param staticDetect
     * @return
     */
    public StaticDetectResult staticDetect(final StaticDetect staticDetect) {
        try {
            return this.execute(new Callback<StaticDetectResult>() {
                @Override
                public StaticDetectResult callback(FaceRecognitionPrx helloWorld) {
                    String data = Base.beanToXml(staticDetect, StaticDetect.class);
                    String value = helloWorld.send(data);
                    StaticDetectResult result = (StaticDetectResult) Base.xmlToBean(value, StaticDetectResult.class);
                    return result;
                }

            });
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 3 人脸验证接口 判断是否同一个人
     *
     * @param compare
     * @return
     */
    public CompareResult compare(final Compare compare) {
        return this.execute(new Callback<CompareResult>() {
            @Override
            public CompareResult callback(FaceRecognitionPrx helloWorld) {
                String data = Base.beanToXml(compare, Compare.class);
                String value = helloWorld.send(data);
                CompareResult result = (CompareResult) Base.xmlToBean(value, CompareResult.class);
                return result;
            }

        });
    }



}


相关文章

网友评论

      本文标题:行为型模式-模板方法模式

      本文链接:https://www.haomeiwen.com/subject/iulhyhtx.html