[设计模式总结] 7. 模板方法模式 -封装算法
引子
例如有两个处理逻辑:泡茶、冲咖啡;
他们的基本流程(算法)是相同的:煮开水、冲泡、倒进杯子、加入调料。只不过具体到个别步骤可能有差异。
如果分成两个类来实现,就会存在重复代码。
——可以将公共的部分(算法)提到父类中;由各个子类实现每个具体步骤。
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
模板方法模式在一个方法中定义算法的框架,而将一些算法步骤延迟到子类中定义。使得子类可以在不改变算法结构的情况下,重新定义算法的某些步骤。——即,封装算法
// Beans public static Object instantiate(ClassLoader cls, String beanName, BeanContext beanContext, AppletInitializer initializer) throws IOException, ClassNotFoundException { // If it was deserialized then it was already init-ed. // Otherwise we need to initialize it. if (!serialized) { // We need to set a reasonable initial size, as many // applets are unhappy if they are started without // having been explicitly sized. applet.setSize(100,100); applet.init(); //调用hook } } return result; }