• Java设计模式 Design Pattern:模板方法 Template Method


    意图

    • 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.
    • 模板方法使得子类可以重新定义算法中的某些步骤而保持算法的结构不变

    结构

     

    • AbstractClass : defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm. implements a template method defining the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects.
    • 抽象类:定义抽象的主要操作,使得具体子类可以去定义实现算法的步骤.实现模板方法中定义的算法骨架.模板方法调用主要操作和抽象类中定义的其他对象.
    • ConcreteClass : implements the primitive operations to carry out subclass-specific steps of the algorithm.
    • 具体子类:实现主要操作,来实施子类特殊的算法步骤.

    应用场景

    • to implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary.
    • 一次性定义算法中不变的部分,将变换部分的实现留给子类.
    • when common behavior among subclasses should be factored and localized in a common class to avoid code duplication. This is a good example of "refactoring to generalize" as described byOpdyke and Johnson. You first identify the differences in the existing code and then separate the differences into new operations. Finally, you replace the differing code with a template method that calls one of these new operations.
    • 当子类中的通用行为应该被改造和重新定义到一个公共类中来避免代码重复时.这是一个泛化来重构的很好的例子,就像Opdyke Johnson描述的那样.你首先识别现有代码中的不同点,然后将他们分离到不同的新操作中.最终,你将不同点代码改为在模板方法中调用这些操作.
    • to control subclasses extensions. You can define a template method that calls "hook" operations (see Consequences) at specific points, thereby permitting extensions only at those points.
    • 为了控制子类扩展,你可以定义模板方法来在某些特定点调用”hook”操作(看作用效果),同时确保只能在那些点扩展.

    影响效果

    • Template methods are a fundamental technique for code reuse. They are particularly important in class libraries, because they are the means for factoring out common behavior in library classes.
    • 模板方法是代码重用技术的基础.他们在类库中很重要,很受欢迎.因为他们意味着在类库中提炼出公共的行为.
    • Template methods lead to an inverted control structure that's sometimes referred to as "the Hollywood principle," that is, "Don't call us, we'll call you" . This refers to how a parent class calls the operations of a subclass and not the other way around.
    • 模板方法导致了一种反向控制结构,有时被解释为好莱坞原则”,不要调用我,我会调用你的.这意味着是父类来调用子类的操作,而不是相反的方向.

     

  • 相关阅读:
    javascript优化--10模式(设计模式)01
    javascript优化--09模式(代码复用)02
    限制字符个数显示
    title
    点选词高亮算法
    ng-repeat嵌套的$index
    console.log的问题
    outsideClick 功能,探索
    input 框的 placeholder 另类实现
    ie9 与 placeholder 问题
  • 原文地址:https://www.cnblogs.com/oyjj/p/2132948.html
Copyright © 2020-2023  润新知