5.8.2 利用组合实现复用

来源:互联网 发布:motion mac 编辑:程序博客网 时间:2024/06/06 12:59

对于继承而言,子类可以直接获得父类的public方法,程序使用子类时,都可以直接访问该子类从父类那里继承到的方法;而组合则是把旧类对象作为新类的成员变量组合起来,用以实现新类的功能。

package chap5_7;class Animal {    private void beat() {        System.out.println("心脏跳动......");    }    public void breath() {        beat();        System.out.println("吸一口气,吐一口气,呼吸中......");    }}class Bird extends Animal {    public void fly() {        System.out.println("我在天空自在的飞翔.....");    }}class Wolf extends Animal {    public void run() {        System.out.println("我在陆地上快速的奔跑......");    }}public class InheritTest {    public static void main(String[] args) {        // TODO Auto-generated method stub        Bird b = new Bird();        b.breath();        b.fly();        Wolf w = new Wolf();        w.breath();        w.run();    }}
package chap5_7;class Animal {    private void beat() {        System.out.println("心脏跳动......");    }    public void breath() {        beat();        System.out.println("吸一口气,吐一口气,呼吸中......");    }}class Bird {    private Animal a;    public Bird(Animal a) {        // TODO Auto-generated constructor stub        this.a = a;    }    public void breath() {        a.breath();    }    public void fly() {        System.out.println("我在天空自在的飞翔.....");    }}class Wolf {    private Animal a;    public Wolf(Animal a) {        // TODO Auto-generated constructor stub        this.a = a;    }    public void breath() {        a.breath();    }    public void run() {        System.out.println("我在陆地上快速的奔跑......");    }}public class CompositeTest {    public static void main(String[] args) {        // TODO Auto-generated method stub        Animal a1 = new Animal();        Bird b = new Bird(a1);        b.breath();        b.fly();        Animal a2 = new Animal();        Wolf w = new Wolf(a2);        w.breath();        w.run();    }}

运行结果

心脏跳动......吸一口气,吐一口气,呼吸中......我在天空自在的飞翔.....心脏跳动......吸一口气,吐一口气,呼吸中......我在陆地上快速的奔跑......

如果采用组合的设计方式,先创建被嵌入类实例,此时需要分配2块内存空间,再创建整体类实例,也需要分配3块内存空间,只是需要多一个引用变量来引用被嵌入的对象。通过这个分析来看,继承设计与组合设计的系统开销不会有本质的差别。
如果Person类需要复用Arm类的方法,此时就应该采用组合关系来实现复用。
继承要表达的是一种 是 is-a的关系,而组合表达的是有 has a的关系。

0 0
原创粉丝点击