星空网 > 软件开发 > ASP.net

《大话设计模式学习笔记》3:装饰模式

  《大话设计模式学习笔记》3:装饰模式

穿衣服示例:

  《大话设计模式学习笔记》3:装饰模式

1.ConcreteComponent(人类):

  public class Person  {    public virtual void Show()    {      Console.Write("开始装扮:");    }  }

2.Decorator(服饰类):

  public class Finery:Person  {    protected Person component;    public void Decorate(Person component)    {      this.component = component;    }    public override void Show()    {      if(component!=null)      {        component.Show();      }    }  }

3.ConcreteDecorator(具体服饰类,以垮裤类为例):

  public class BigTrouser:Finery  {    public override void Show()    {      base.Show();//首先运行原Component的操作,再执行本类的操作      Console.Write("垮裤 ");    }  }

4.客户端代码:

  class Program  {    static void Main(string[] args)    {      Person person = new Person();      BigTrouser bigTrouser = new BigTrouser();      TShirts tShirts = new TShirts();       LeatherShoes leatherShoes = new LeatherShoes();      bigTrouser.Decorate(person);      tShirts.Decorate(bigTrouser);      leatherShoes.Decorate(tShirts);      leatherShoes.Show();    }  }

  如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。同样道理,如果只有一个ConcreteDecorator类,那就没有必要建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。

 

  装饰模式是为已有功能动态添加更多功能的一种方式。

  优点:有效地把类的核心职责和装饰功能区分开,而且可以去除相关类中重复的逻辑。




原标题:《大话设计模式学习笔记》3:装饰模式

关键词:设计模式

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

传统电商转型必看:跨境电商布局全球化趋势明显!:https://www.ikjzd.com/articles/95749
亚马逊推新规,相关类目的卖家需注意!:https://www.ikjzd.com/articles/95750
韭菜割不停?中国卖家占亚马逊总卖家6成以上?:https://www.ikjzd.com/articles/95753
新手卖家创业选择亚马逊无货源铺货模式的7大理由!:https://www.ikjzd.com/articles/95755
Shopee新手有问必答!:https://www.ikjzd.com/articles/95756
全面分析:解读我国Q1季度网络零售市场发展态势!:https://www.ikjzd.com/articles/95757
37号文今后是否会更新?一文详解关键信息 :https://www.kjdsnews.com/a/1836441.html
探讨内地人开设香港账户的可行性 :https://www.kjdsnews.com/a/1836442.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流