装饰静态 class C#
Decorating a static class C#
我有一个设计问题。
我在一些旧代码中使用了一个静态 class 调用静态方法来 运行 一些操作。如果满足某个条件,我想紧接着调用另一个方法。
我想使用装饰器模式,但如果不满足条件,我不能完全 return 静态实例 class。
这就是现在正在发生的事情。
var result = StaticClass.DoSomething(some parameters);
如果另一个变量为真,我想要的是在调用 DoSomething 之后立即写入数据库,我不想只是用条件堆砌旧代码,所以我宁愿将其委托给某些人其他 class。这才是我真正想做的。
var result = StaticClassFactory(condition).DoSomething(some parameters);
Class1
void DoSomething(parameters) {
StaticClass.DoSomething()
}
Class2
void DoSomething(parameters) {
StaticClass.DoSomething();
DoSomethignElse();
}
有什么建议吗?
你可以做的是使用一个接口来表示 "doer":
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();
}
}
然后使用工厂return根据条件实现IDoer的实例:
public class DoerFactory
{
public IDoer GetDoer(object someCondition)
{
//Determine which instance to create and return it here
}
}
由于没有更多信息可用,我对某些内容使用了 object
类型的占位符。
我有一个设计问题。
我在一些旧代码中使用了一个静态 class 调用静态方法来 运行 一些操作。如果满足某个条件,我想紧接着调用另一个方法。
我想使用装饰器模式,但如果不满足条件,我不能完全 return 静态实例 class。
这就是现在正在发生的事情。
var result = StaticClass.DoSomething(some parameters);
如果另一个变量为真,我想要的是在调用 DoSomething 之后立即写入数据库,我不想只是用条件堆砌旧代码,所以我宁愿将其委托给某些人其他 class。这才是我真正想做的。
var result = StaticClassFactory(condition).DoSomething(some parameters);
Class1
void DoSomething(parameters) {
StaticClass.DoSomething()
}
Class2
void DoSomething(parameters) {
StaticClass.DoSomething();
DoSomethignElse();
}
有什么建议吗?
你可以做的是使用一个接口来表示 "doer":
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();
}
}
然后使用工厂return根据条件实现IDoer的实例:
public class DoerFactory
{
public IDoer GetDoer(object someCondition)
{
//Determine which instance to create and return it here
}
}
由于没有更多信息可用,我对某些内容使用了 object
类型的占位符。