首页 > 其他 > 详细

装饰者模式

时间:2014-05-01 05:33:57      阅读:379      评论:0      收藏:0      [点我收藏+]

首先:我们建立一个超类:Clothes:

bubuko.com,布布扣
    public abstract class Clothes
    {
         public string Look = "beautiful";

        public string Getlook()
        {
            return Look;
        }

        public abstract double Cost();
    }
bubuko.com,布布扣

考虑到将不同的独立出来:我们写一个类:此类暂时和本方向无关,可以不注意Dress:

    public abstract class Dress : Clothes
    {
        public  abstract string WithWho();
    }

衣服有不同的,我们独立出2种来:Lap与Pants:

bubuko.com,布布扣
    public class Lap : Clothes
    {
        public Lap ()
        {
            Look = "more beautiful with lap";
        }

        public override double Cost()
        {
            return 100;
        }
    }
    public class Pants : Clothes
    {
        public Pants ()
        {
            Look = "more beautiful with pants";
        }

        public override double Cost()
        {
            return 88;
        }
    }
bubuko.com,布布扣

这个时候我们写一个装饰品类出来装饰Lap与Pants,此类Bag(注意此类必须继承Clothes):

bubuko.com,布布扣
    public class Bag : Dress
    {
        public Clothes Clothes;

        public Bag(Clothes clothes)
        {
            Clothes = clothes;
            Look = Clothes.Getlook() +WithWho()+ " bag";
        }

        public override sealed string WithWho()
        {
            return "need";
        }

        public override double Cost()
        {
            return 10 + Clothes.Cost();
        }
    }
bubuko.com,布布扣

这个时候我们就可以装饰他了:

bubuko.com,布布扣
        static void Main(string[] args)
        {
            Clothes clothes=new Lap();
            Console.WriteLine(clothes.Getlook()+" need "+clothes.Cost());
            Clothes clothes2=new Pants();
            clothes2=new Bag(clothes2);
            clothes2=new Bag(clothes2);
            Console.WriteLine(clothes2.Getlook() + " need " + clothes2.Cost());
            Console.ReadLine();
        }
bubuko.com,布布扣

结果为:more beautiful with lap need 100

           more beautiful with pantsneed bagneed bag need 108

此模式好处:1、此模式能解决独立的类过多的问题

                 2、我们需要加什么装饰非常容易

 

装饰者模式,布布扣,bubuko.com

装饰者模式

原文:http://www.cnblogs.com/junyong/p/3701985.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!