[英]Decorating a static class C#
I've got a design question. 我有一个设计问题。
I've got a static class used in some old code that calls a static method to run some operation. 我在一些旧代码中使用了一个静态类,该类调用一个静态方法来运行某些操作。 If a certain condition is met, I want to call another method right after it.
如果满足特定条件,我想在它之后立即调用另一个方法。
I wanted to use the decorator pattern but I can't exactly return an instance of the static class if the condition is not met. 我想使用装饰器模式,但如果不满足条件,则无法完全返回静态类的实例。
This is what's happening now. 这就是现在正在发生的事情。
var result = StaticClass.DoSomething(some parameters);
What I want is to write to a database right after that DoSomething is called if another variable is true and I didn't want to just pile on to the old code with conditionals so I'd rather delegate that to some other class. 我想要的是在另一个变量为true的情况下,在调用DoSomething之后立即将其写入数据库,而我不想只将带条件的代码堆放在旧代码上,所以我宁愿将其委托给其他类。 This is what I really want to do.
这就是我真正想做的。
var result = StaticClassFactory(condition).DoSomething(some parameters);
Class1
void DoSomething(parameters) {
StaticClass.DoSomething()
}
Class2
void DoSomething(parameters) {
StaticClass.DoSomething();
DoSomethignElse();
}
Any suggestions? 有什么建议么?
What you can do is use an interface to represent the "doer": 您可以做的是使用一个接口来表示“执行者”:
public interface IDoer
{
void DoSomething(object parameters);
}
Then create the two classes: 然后创建两个类:
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();
}
}
Then use a factory to return an instance that implements IDoer based on the condition: 然后使用工厂返回根据条件实现IDoer的实例:
public class DoerFactory
{
public IDoer GetDoer(object someCondition)
{
//Determine which instance to create and return it here
}
}
I used placeholders of type object
for some things as no more information is available. 由于没有更多信息,我在某些情况下使用了
object
类型的占位符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.