gpt4 book ai didi

c# - 装饰静态类 C#

转载 作者:行者123 更新时间:2023-12-04 14:25:12 25 4
gpt4 key购买 nike

我有一个设计问题。

我在一些旧代码中使用了一个静态类,它调用静态方法来运行某些操作。如果满足某个条件,我想在它之后立即调用另一个方法。

我想使用装饰器模式,但如果不满足条件,我不能准确地返回静态类的实例。

这就是现在发生的事情。

var result = StaticClass.DoSomething(some parameters);

我想要的是在另一个变量为真时调用 DoSomething 之后立即写入数据库,我不想只用条件语句堆砌到旧代码上,所以我宁愿将其委托(delegate)给其他类.这是我真正想做的。

var result = StaticClassFactory(condition).DoSomething(some parameters);

Class1
void DoSomething(parameters) {
StaticClass.DoSomething()
}

Class2
void DoSomething(parameters) {
StaticClass.DoSomething();
DoSomethignElse();
}

有什么建议吗?

最佳答案

你可以做的是使用一个接口(interface)来表示“执行者”:

public interface IDoer
{
void DoSomething(object parameters);
}

然后创建两个类:

public class DefaultDoer : IDoer
{
public void DoSomething(object parameters)
{
StaticClass.DoSomething(object parameters);
}
}

public class AugmentedDoer : IDoer
{
public void DoSomething(object parameters)
{
StaticClass.DoSomething(object parameters);
DoSomethingElse();
}
}

然后根据条件使用工厂返回一个实现IDoer的实例:

public class DoerFactory
{
public IDoer GetDoer(object someCondition)
{
//Determine which instance to create and return it here
}
}

由于没有更多信息可用,我对某些内容使用了 object 类型的占位符。

关于c# - 装饰静态类 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47160880/

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