C# 装饰模式(Decorate)
作用:针对已经有固定功能的类,想要添加新的小功能或者属性,把这些小功能或者属性放到装饰类里,客户端可以动态地选择用哪些装饰类去修饰原有的类。代码如下:
using System.Windows.Forms;
namespace DesignMode.Decorate
{
//手机
public class Mobile
{
public virtual void Play()
{
MessageBox.Show("Play Mobile");
}
}
//装饰类
public class MyDecorate : Mobile
{
protected Mobile _mobile;
public void Decorate(Mobile mobile)
{
this._mobile = mobile;
}
public override void Play()
{
if (_mobile != null)
{
_mobile.Play();
}
}
}
public class OpenGPS : MyDecorate
{
public override void Play()
{
MessageBox.Show("开通GPS");
base.Play();
}
}
public class Shell : MyDecorate
{
public override void Play()
{
MessageBox.Show("装上外壳");
base.Play();
}
}
public class Alarm : MyDecorate
{
public override void Play()
{
MessageBox.Show("设定闹钟");
base.Play();
}
}
namespace DesignMode.Decorate
{
//手机
public class Mobile
{
public virtual void Play()
{
MessageBox.Show("Play Mobile");
}
}
//装饰类
public class MyDecorate : Mobile
{
protected Mobile _mobile;
public void Decorate(Mobile mobile)
{
this._mobile = mobile;
}
public override void Play()
{
if (_mobile != null)
{
_mobile.Play();
}
}
}
public class OpenGPS : MyDecorate
{
public override void Play()
{
MessageBox.Show("开通GPS");
base.Play();
}
}
public class Shell : MyDecorate
{
public override void Play()
{
MessageBox.Show("装上外壳");
base.Play();
}
}
public class Alarm : MyDecorate
{
public override void Play()
{
MessageBox.Show("设定闹钟");
base.Play();
}
}
}
客户端代码:
private void btn_Decorate_Click(object sender, EventArgs e)
{
Mobile mobile = new Mobile();
//设闹钟,开通GPS
OpenGPS gps = new OpenGPS();
Alarm alarm = new Alarm();
gps.Decorate(mobile);
alarm.Decorate(gps);
alarm.Play();
{
Mobile mobile = new Mobile();
//设闹钟,开通GPS
OpenGPS gps = new OpenGPS();
Alarm alarm = new Alarm();
gps.Decorate(mobile);
alarm.Decorate(gps);
alarm.Play();
}