组合 到底能起什么作用?

解决方案 »

  1.   

    多用组合少用继承
    多看些软件工程的book
      

  2.   

    Design Pattern的建议:
    1。针对接口编程
    2。邮箱使用组合,而不是继承
    3。找到并封装变化点
    组成是被包容的对象是包容对象的一部分,即缺少了不可,例如引擎对于汽车
      

  3.   

    简单的说,组合就是一种“has-a”的关系,只要你的类体系中类和类之间的关系属于一个拥有另一个的关系,就要用到组合。
    而相对的继承,就是一种“is-a”的关系。
      

  4.   

    “组合”是代码复用的一种有效手段,帮助你通过不同数据类型之间的融合产生新的更具威力的类型。
        不同于继承,虽然两者都是复用的极佳工具,但组合提供了一种动态体系结构,使得你可以更灵活的在运行时决定调用的类型,而继承是一种静态体系结构,一旦继承就无法改变父子关系。继承代码重用的事例:
    class Father {
      protected int i = 5;
      protected void print() {
        System.out.println("This 'i' is belong to Father, but be called from Son: " + i);
      }
    }class Son extends Father { }class Test {
      public static void main(String[] args) {
        Son s = new Son();
        // Call print() method
        s.print();
      }
    }使用复合支持代码重用
    class Component {
      private int i = 5;
      public void print() {
        System.out.println("This 'i' is belong to Component, but be called from Son: " + i);
      }
    }class Another {
      private Component c = new Component();
      public void print() {
        c.print();
      }
    }class Test {
      public static void main(String[] args) {
        Another other = new Another();
        // Call print() method
        other.print();
      }
    }@.@||~
      

  5.   

    midthinker(呵呵) 用了关联中的聚合或者是合成关系