• Chapter 02:复合 VS 继承


    复合优先于继承,继承是实现代码重用的有力手段,并不是所有情况都适用,使用不当会导致软件变得很脆弱。与方法调用不同的是,继承打破了封装性。

    总而言之,组合和继承,都能实现对类的扩展。但是要分具体情况用哪个实现,是Has-a,还是Is-a的关系。

    两者区别如下表所示:

    组合 继承
    has-a关系 is-a关系
    运行期决定 编译期决定
    不破坏封装,整体和局部松耦合 破坏封装,子类依赖父类
    支持扩展,随意增加组合类 只能继承一个父类,必须包含所有方法,增加系统复杂性
    动态选择组合类方法 复用父类方法

                                         来自 :http://blog.csdn.net/wangpeifeng669/article/details/26403119

    Decorator模式对组合的应用是最经典诠释:

    上码

      
    public Ice(Product product) {  
        this.product = product;  
    }  
      
    public double money() {  
        return product.money() + 1.5;  
    }  
    }  
      
    //加奶:  
    class Milk implements Product {  
    private Product product;  
      
    public Milk(Product product) {  
        this.product = product;  
    }  
      
    public double money() {  
        return product.money() + 4.0;  
    }  
    }  
      
    //加巧克力:  
    class Chocolate implements Product {  
    private Product product;  
      
    public Chocolate(Product product) {  
        this.product = product;  
    }  
      
    public double money() {  
        return product.money() + 5.5;  
    }  
    }  
    public class DecoratorModel{  
    public static void main(String [] args){  
        Product coffee = new Coffee();  
        Product sugarCoffee = new Sugar(coffee);  
        Product sugarmilkCoffee = new Milk(sugarCoffee);  
        System.out.println("加糖咖啡:"+sugarCoffee.money());  
        System.out.println("加糖加奶咖啡:"+sugarmilkCoffee.money());  
    }  
    }  

    来自http://www.cnblogs.com/shipengzhi/articles/2086419.html

      

  • 相关阅读:
    Java小细节
    LinkedHashMap的accessOrder的作用
    异或运算及其应用
    什么是FullStack设计
    Java正则表达式收藏
    offsetLeft,Left,clientLeft的区别
    java文件常用操作(2) 从文件末尾开始读取文件
    java文件常用操作
    各种排序方法
    2013微软暑期实习笔试&面试总结
  • 原文地址:https://www.cnblogs.com/spring87/p/5638322.html
Copyright © 2020-2023  润新知