首页 > 代码库 > 装饰模式
装饰模式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*
装饰模式
*
* 定义接口或类(类或抽象类)
* 分类实现
* 如多种对象类 A 或 B
* 使用继承实现B类多样代处理和自己的处理
*
* 调用
* 定义A类 定义B类
* 把A类代入B类调用B类为A装饰
* 再把装饰好的B类代入后面的B1类中装饰
*
*
*/
namespace App_MYCS.HDL_SJMS.ZSMS
{
class my_ZSMS
{
//调用方式1
public void zsmsdy()
{
person xc = new person("人小菜");
zsms_class_zl1 zsms_zl1 = new zsms_class_zl1();
zsms_class_zl2 zsms_zl2 = new zsms_class_zl2();
zsms_zl1.Decorate(xc);
zsms_zl2.Decorate(zsms_zl1);
zsms_zl1.show();
}
//调用方式2
public void zsmsdy1()
{
ConcreteComponent c = new ConcreteComponent();
concreteDecoratorA d1 = new concreteDecoratorA();
concreteDecoratorB d2 = new concreteDecoratorB();
d1.SetComponet(c);
d2.SetComponet(d1);
d2.Operation();
}
}
#region 方式1
/// <summary>
/// 定义一个对象接口
/// 可以给这些对象动态的增加职责
/// </summary>
abstract class compoent
{
public abstract void Operation();
}
//--------------------------------------------------------
class ConcreteComponent : compoent
{
public override void Operation()
{
Console.WriteLine("具体对象的操作");
}
}
abstract class Decorator : compoent
{
protected compoent compoent;
public void SetComponet(compoent compoent)
{
this.compoent = compoent;
}
public override void Operation()
{
if (compoent != null)
{
compoent.Operation();
}
}
}
//--------------------------------------------------------
class concreteDecoratorA : Decorator
{
private string addedstate;
public override void Operation()
{
//选运行父类的Operation方法 (先后不是关键)
base.Operation();
//再执行本类的独有的方法
addedstate = "new addedstate";
Console.WriteLine("具体装饰对象A对象");
}
}
class concreteDecoratorB : Decorator
{
private string addedstate;
public override void Operation()
{
//选运行父类的Operation方法
base.Operation();
//再执行本类的独有的方法
AddedBehavior();
Console.WriteLine("具体装饰对象B对象");
}
//本类独有的方法
private void AddedBehavior()
{
}
}
#endregion
#region 方式2
//--------------------------------------------------------
class person
{
public person()
{
}
private string name;
public person(string name)
{
this.name = name;
}
public virtual void show()
{
Console.WriteLine();
}
}
class Finery : person
{
protected person component;
//
public void Decorate(person component)
{
this.component = component;
}
public override void show()
{
if (component != null)
{
component.show();
}
}
}
//--------------------------------------------------------
class zsms_class_zl1 : Finery
{
public override void show()
{
Console.WriteLine("zsms_class_zl1");
base.show();
}
}
class zsms_class_zl2 : Finery
{
public override void show()
{
Console.WriteLine("zsms_class_zl2");
base.show();
}
}
#endregion
}
装饰模式