使用委派代替继承

#region 使用委派代替继承
    /*概念:本文中的“使用委派代替继承”是指在根本没有父子关系的类中使用继承是不合理的,
            可以用委派的方式来代替。*/
    /*正文:如下代码所示,Child 和 Sanitation (公共设施)是没有逻辑上的父子关系,因为小
            孩不可能是一个公共设施吧!所以以下这种继承就显得不合理*/
    #region 1.继承方式 (应用场景不合理)
    ///// <summary>
    ///// 公共设施类
    ///// </summary>
    //public class Sanitation
    //{
    //    public string WashHands()
    //    {
    //        return "Cleaned!";
    //    }
    //}
    ///// <summary>
    ///// 小孩
    ///// </summary>
    //public class Child : Sanitation
    //{
    //}
    #endregion

    #region 2.委派方式
    /*重构后的代码如下,把Sanitation 委派到Child 类中,从而可以使用WashHands 这个方
        法,这种方式我们经常会用到,其实IOC 也使用到了这个原理,可以通过构造注入和方法
        注入等。*/
    /*总结:这个重构是一个很好的重构,在很大程度上解决了滥用继承的情况,很多设计模式也
            用到了这种思想(比如桥接模式、适配器模式、策略模式等)。*/
    /// <summary>
    /// 公共设施
    /// </summary>
    public class Sanitation
    {
        public string WashHands()
        {
            return "Cleaned!";
        }
    }
    /// <summary>
    /// 小孩
    /// </summary>
    public class Child
    {
        private Sanitation Sanitation { get; set; }
        public Child()
        {
            Sanitation = new Sanitation();
        }
        public string WashHands()
        {
            return Sanitation.WashHands();
        }
    }
    #endregion
    #endregion
posted @ 2012-12-03 14:42  小罗》  阅读(177)  评论(0)    收藏  举报