gpt4 book ai didi

c# - 多接口(interface)装饰

转载 作者:太空狗 更新时间:2023-10-29 21:42:38 28 4
gpt4 key购买 nike

我一直在纠结于装饰+接口(interface)。假设我有以下“行为”接口(interface):

interface IFlyable { void Fly();}
interface ISwimmable { void Swim();}

主界面

interface IMainComponent { void DoSomethingA(); void DoSomethingB();}

主界面上的装饰器

    public class Decorator : IMainComponent
{
private readonly IMainComponent decorated;
[..]

public virtual void DoSomethingA()
{
decorated.DoSomethingA();
}

public virtual void DoSomethingB()
{
decorated.DoSomethingB();
}
}

我的问题是如何将装饰对象实现的所有接口(interface)转发给装饰器。一种解决方案是使装饰器实现接口(interface):

    public class Decorator : IMainComponent, IFlyable, ISwimmable
{
[..]

public virtual void Fly()
{
((IFlyable)decorated).Fly();
}

public virtual void Swim()
{
((ISwimmable)decorated).Swim();
}

但我不喜欢它,因为:

  1. 它可能看起来像“装饰器”实现了一个接口(interface),但实际上并非如此(运行时抛出异常)
  2. 这是不可扩展的,我需要添加每个新接口(interface)(并且不要忘记这个添加)

另一种解决方案是添加传播装饰树的“手动转换”:

    public class Decorator : IMainComponent
{
public T GetAs<T>()
where T : class
{
//1. Am I a T ?
if (this is T)
{
return (T)this;
}

//2. Maybe am I a Decorator and thus I can try to resolve to be a T
if (decorated is Decorator)
{
return ((Decorator)decorated).GetAs<T>();
}

//3. Last chance
return this.decorated as T;
}

但问题是:

  1. 调用方可以在调用 GetAs() 之后操作包装的对象。
  2. 如果在调用 GetAs 之后使用 IMainComponent 中的方法(类似于 ((IMainComponent)GetAs()).DoSomethingB(); ==> 这可能会调用包装对象的实现),这可能会导致混淆/不需要的行为,而不是完整的装饰。
  3. 需要调用 GetAs() 方法,退出带有强制转换/常规“As”的代码将不起作用。

您如何处理/解决这个问题?是否有解决此问题的模式?

PD:我的问题是关于最终的 C# 实现,但解决方案可能更广泛。

最佳答案

您需要为每个界面创建单独的装饰器。另一种方法是为您的服务使用通用接口(interface)和通用装饰器。例如:

public interface ICommandService<TCommand>
{
Task Execute(TCommand command);
}

public class LoggingCommandService<TCommand> : ICommandService<TCommand>
{
public LoggingCommandService(ICommandService<TCommand> command, ILogger logger)
{
...
}

public async Task Execute(TCommand command)
{
// log
await this.command.Execute(command);
// log
}
}

关于c# - 多接口(interface)装饰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55166176/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com