Differences between combination, inheritance, and proxy
- Three definitions:
- Combination: adds the object of another class in the new class to add the features of this object.
- Inheritance: Get the subclass from the base class to obtain the features of the base class.
- Proxy: Creates a function class in the proxy class and calls some methods of the class to obtain some features of the class.
- Usage:
- Combination: there is no relationship between components. You only need to combine them. Like assembling a computer, new CPU (), new RAM (), new Disk ()......
The Demo code is as follows:
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{ }
- Inheritance: Child classes must have the function of parent classes, which are different from each other. The like Shape class is used as the base class, and its subclasses include Rectangle, CirCle, Triangle ...... Code is not written, and is often used.
- Proxy: aircraft control class. I don't want to expose too many aircraft control functions. I only need to control the movement of the plane (instead of exposing the missile launching function ). Add a new aircraft control object in the proxy class, and then add the required functions of the aircraft control class in the method.
The Demo code is as follows:
1 public class PlaneDelegation {2 private PlaneControl planeControl; // private external inaccessible 3/* 4 * pilot permission proxy class, normal pilots cannot open fire 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 indicates that the class cannot be inherited, and the controller can be inherited .. 21 protected void speed () {} 22 protected void fire () {} 23 protected void left () {} 24 protected void right () {} 25}