装饰者模式
来源:互联网 发布:淘宝网长袖t恤高端 编辑:程序博客网 时间:2024/06/03 21:36
//装饰模式
优点
1、装饰者模式可以提供比继承更多的灵活性
2、可以通过一种动态的方式来扩展一个对象的功能,在运行时选择不同的装饰器,从而实现不同的行为。
3、通过使用不同的具体装饰类以及这些装饰类的排列组合,可以创造出很多不同行为的组合。可以使用多个具体装饰类来装饰同一对象,得到功能更为强大的对象。
4、具体构件类与具体装饰类可以独立变化,用户可以根据需要增加新的具体构件类和具体装饰类,在使用时再对其进行组合,原有代码无须改变,符合“开闭原则”。
缺点
1、会产生很多的小对象,增加了系统的复杂性
2、这种比继承更加灵活机动的特性,也同时意味着装饰模式比继承更加易于出错,排错也很困难,对于多次装饰的对象,调试时寻找错误可能需要逐级排查,较为烦琐。
装饰者模式的适用场景
1、在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
2、需要动态地给一个对象增加功能,这些功能也可以动态地被撤销。 当不能采用继承的方式对系统进行扩充或者采用继承不利于系统扩展和维护时。
推荐文章(http://blog.csdn.net/chenssy/article/details/8959039)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Configuration;
namespace yjzcjing
{
class Persion//定义对象接口
{
public Persion()
{ }
public string name;
public Persion(String name)
{
this.name = name;
}
public virtual void Show()
{
Console.WriteLine("装扮的{0}", name);
}
}
class Finery : Persion//装饰类
{
protected Persion component;
public void Decorate(Persion component)//该方法被子类所继承,由此子类在调用此函数进行装饰的时候,将接受对象赋值给了component
//由此,具体装饰类调用Decorate将要装饰用的对象给了父类
{
this.component = component;
}
public override void Show()//base.Show()函数,调用的就是该函数,
{
if (component != null)
{
component.Show();
}
}
}
class TShits : Finery//具体装饰类
{
public void Show()
{
Console.WriteLine("大体恤");
base.Show();
}
}
class BigTrouser : Finery
{
public override void Show()
{
Console.WriteLine("垮裤");
base.Show();
}
}
class Sneakers : Finery
{
public override void Show()
{
Console.WriteLine("破球鞋");
base.Show();
}
}
class Program
{
static void Main(string[] args)
{
Persion yjz = new Persion("贾珍");
Console.WriteLine("装扮如下:");
Sneakers pqx = new Sneakers();
BigTrouser kk = new BigTrouser();
TShits dtk = new TShits();
pqx.Decorate(yjz);
kk.Decorate(pqx);
dtk.Decorate(kk);
dtk.Show();
Console.Read();
}
}
}//该模式,是一种递归
- 装饰者模式(Derector)
- 装饰者模式
- Decorator 装饰者模式
- 装饰者设计模式
- 装饰者模式
- 装饰者模式
- 装饰者模式
- 装饰者模式(Decorator)
- 装饰者模式
- 装饰者模式
- 装饰者模式
- 装饰者模式 DecoratorPattern
- 设计模式 - 装饰者
- 装饰者模式
- 装饰者模式
- 装饰者模式 - 2
- 装饰者模式
- 装饰者模式
- 设计模式-观察者
- HTML5 SVG
- BUI之遮罩层
- 如何搭建大型网站系统
- 剑指offer|旋转数组的最小数字
- 装饰者模式
- JDWP exit error AGENT_ERROR_NO_JNI_ENV(183)
- 一张图带你看懂SpriteKit中Update Loop究竟做了神马!
- word Ladder2
- openGL的安装使用
- socket编程中的一个坑
- 内存溢出
- 1
- ACdream 1210 Chinese Girls' Amusement 大数+思维