zoukankan      html  css  js  c++  java
  • 摸板模式与钩子

    常常会在程序中遇到多个子类有共同的方法以及相似的调用过程。这个时候我们就可以使用模板模式来解决这些重复性的工作,例如我们买东西的时候一般都是挑选商品、付款这样的步骤,区别仅仅是挑选的商品品种不一样而已,这个时候我们就可以使用模板模式。那么模板模式需要怎么来实现呢,如下图

    clip_image002

    代码如下:

    public class test

    {

    public static void main(String args[])

    {

    goods f=new fruit();

    f.run();

    goods d=new drink();

    d.run();

    }

    }

    class goods

    {

    void run()

    {

    getgoods();

    pay();

    }

    void getgoods()

    {

    System.out.println("get");

    }

    void pay()

    {

    System.out.println("pay");

    }

    }

    class fruit extends goods

    {

    void getgoods()

    {

    System.out.println("fruit");

    }

    }

    class drink extends goods

    {

    void getgoods()

    {

    System.out.println("drink");

    }

    }

    结果如图:

    clip_image004

    这样我们就可以避免在子类中涉及具体的算法,只需要将重复的内容已经算法提取到父类即可,降低了耦合。

    至此,我们还可以加入一个钩子的机制,即可相应的对一些不需要的算法来进行控制。

    代码如下

    public class test

    {

    public static void main(String args[])

    {

    goods f=new fruit();

    f.run();

    goods d=new drink();

    d.run();

    }

    }

    class goods

    {

    void run()

    {

    if(hasGetGoods())

    getgoods();

    pay();

    }

    void getgoods()

    {

    System.out.println("get");

    }

    boolean hasGetGoods()

    {

    return false;

    }

    void pay()

    {

    System.out.println("pay");

    }

    }

    class fruit extends goods

    {

    boolean hasGetGoods()

    {

    return true;

    }

    void getgoods()

    {

    System.out.println("fruit");

    }

    }

    class drink extends goods

    {

    boolean hasGetGoods()

    {

    return false;

    }

    void getgoods()

    {

    System.out.println("drink");

    }

    }

    结果:

    clip_image006

    联系我:renhanlinbsl@163.com

    2016-8-3

    21:25

  • 相关阅读:
    ARC 基础(上)
    将字符串写到屏幕上
    UIColor 详解
    the complexity is no longer O(lgn), right?
    [LeetCode] Sum Root to Leaf Numbers, Solution
    [LeetCode] Word Ladder II, Solution
    [Microsoft] Intealeaving of two given strings, Solution
    [Yahoo] Cloest palindrome number, Solution
    [LeetCode] Longest Consecutive Sequence, Solution
    Summary
  • 原文地址:https://www.cnblogs.com/ives/p/template_pattern.html
Copyright © 2011-2022 走看看