【Thinking in Java】組合、繼承和代理的區別

  1. 三者的定義:
    1. 組合:在新類中new 另一個類的對象,以添加該對象的特性。
    2. 繼承:從基類繼承獲得子類,得到基類的特性。
    3. 代理:在代理類中建立某功能的類,調用類的一些方法以得到該類的部分特性。
  1. 使用場合:
  • 組合:各部件之間沒什麼關係,只須要組合便可。like組裝電腦,須要new CPU(),new RAM(),new Disk()……

  演示代碼以下:spa

  

 1 public class Computer {
 2     public Computer() {
 3         CPU cpu=new CPU();
 4         RAM ram=new RAM();
 5         Disk disk=new Disk();
 6     }
 7 }
 8 class CPU{    }
 9 class RAM{    }
10 class Disk{    }

 

  • 繼承:子類須要具備父類的功能,各子類之間有所差別。like Shape類做爲基類,子類有RectangleCirCleTriangle……代碼不寫了,你們都常常用。
  • 代理:飛機控制類,我不想暴露太多飛機控制的功能,只需部分前進左右轉的控制(而不須要暴露發射導彈功能)。經過在代理類中new一個飛機控制對象,而後在方法中添加飛機控制類的各個須要暴露的功能。

  演示代碼以下:代理

 1 public class PlaneDelegation{    
 2     private PlaneControl planeControl;    //private外部不可訪問
 3     /*
 4      * 飛行員權限代理類,普通飛行員不能夠開火
 5      */
 6     PlaneDelegation(){
 7         planeControl=new PlaneControl();
 8     }
 9     public void speed(){
10         planeControl.speed();
11     }
12     public void left(){
13         planeControl.left();
14     }
15     public void right(){
16         planeControl.right();
17     }
18 }
19 
20 final class PlaneControl {//final表示不可繼承,控制器都能繼承那還得了。。
21     protected void speed() {}
22     protected void fire() {}
23     protected void left() {}
24     protected void right() {}
25 }
相關文章
相關標籤/搜索