温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

设计模式-装饰模式

发布时间:2020-07-17 12:50:07 来源:网络 阅读:326 作者:全嗲吉祥 栏目:编程语言
public class Person
    {
        public Person()
        {
        }
        private string name;
        public Person(string _name)
        {
            this.name = _name;
        }        
        public virtual void show()
        {
            Console.WriteLine(string.Format("{0}开始show",name));
        }
    }
public class Fushi:Person
    {
        protected Person person;

        public void daban(Person _person)
        {
            this.person = _person;
        }
        public override void show()
        {
            if (person != null)
            {
                person.show();
            }
        }
    }
    public class xizhuang : Fushi
    {
        public override void show()
        {
            Console.WriteLine("穿了西装");
            base.show();
        }
    }
    public class xiku : Fushi
    {
        public override void show()
        {
            Console.WriteLine("穿了西裤");
            base.show();
        }
    }
    public class pixie : Fushi
    {
        public override void show()
        {
            Console.WriteLine("穿了皮鞋");
            base.show();
        }
    }
    public class duanxiu : Fushi
    {
        public override void show()
        {
            Console.WriteLine("穿了短袖");
            base.show();
        }
    }
    public class niuzaiku : Fushi
    {
        public override void show()
        {
            Console.WriteLine("穿了牛仔裤");
            base.show();
        }
    }
    public class fanbuxie : Fushi
    {
        public override void show()
        {
            Console.WriteLine("穿了帆布鞋");
            base.show();
        }
    }
前端
Person p = new Person("张三");
Fushi f1 = new xizhuang();
Fushi f2 = new xiku();
Fushi f3 = new pixie();
f1.daban(p);
f2.daban(f1);
f3.daban(f2);            
f3.show();

设计模式-装饰模式
总结:装饰模式是为已有功能动态添加更多功能的一种方式。
错误的设计方法是当系统需要新功能时,向类中添加新的代码。这些新加的代码通常装饰了原有类的主要行为,同时增加了类的复杂度;并且违背开闭原则。
装饰模式把每个需要装饰的功能单独放到一个类中,并让类包装他需要装饰的对象。
优点:可以简化要装饰的类,把核心职责和装饰功能分离,去除重复逻辑

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI