装饰器接口
public interface IDecorator
{
string DecoratorAction();
}
被装饰的类
[StopRing]
[MetalimBeam]
[PunchLaser]
public class Ultraman : IDecorator
{
private string name;
public Ultraman(string name)
{
this.name = name;
}
public string DecoratorAction()
{
return name;
}
}
装饰类的基类
[AttributeUsage(AttributeTargets.Class)]
public abstract class BeamAttribute : Attribute, IDecorator
{
protected IDecorator decorator;
public BeamAttribute()
{
}
public void SetDecorator(IDecorator decorator)
{
this.decorator = decorator;
}
public abstract string DecoratorAction();
}
第一个装饰类
public class StopRing : BeamAttribute
{
public override string DecoratorAction()
{
return decorator.DecoratorAction() + " 止动环";
}
}
第二个装饰类
public class MetalimBeam : BeamAttribute
{
public override string DecoratorAction()
{
return decorator.DecoratorAction() + " 美塔林光线";
}
}
第三个装饰类
public class PunchLaser : BeamAttribute
{
public override string DecoratorAction()
{
return decorator.DecoratorAction() + " 普拉斯光线";
}
}
装饰类工厂
public class DecoratorFactory
{
public static IDecorator GetUltraman(string name)
{
Ultraman ultraman = new Ultraman(name);
return SetUltramanBeam(ultraman);
}
private static IDecorator SetUltramanBeam(Ultraman ultraman)
{
Type type = typeof(Ultraman);
var beams = type.GetCustomAttributes(false);
IDecorator foreBeam = null;
foreach ( var beam in beams )
{
BeamAttribute currentBeam = beam as BeamAttribute;
if (foreBeam == null ) {
currentBeam.SetDecorator(ultraman);
}
else
{
currentBeam.SetDecorator(foreBeam);
}
foreBeam = currentBeam;
}
return foreBeam;
}
}
program启动
internal class Program
{
static void Main(string[] args)
{
var aa = DecoratorFactory.GetUltraman("ace").DecoratorAction();
}
}
分类:
学习笔记
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义