【发布时间】:2012-08-18 07:40:46
【问题描述】:
我正在重构一些遗留代码,这些代码通过一个案例语句一遍又一遍地做着相似的事情:
switch(identifier)
case firstIdentifier:
(SomeCast).SetProperties(Prop1,Prop2,Prop3);
break;
...
case anotherIdentifier:
(SomeDifferentCast).SetProperties(Prop1, Prop2, Prop3);
break;
所以,我尝试创建一个独特的界面,以便它可以成为
(SameInterfaceCast).SetProperties(Prop1,Prop2,Prop3);
但是,我随后发现有些项目甚至没有使用所有属性。于是,我开始想到更像这样的东西:
if(item is InterfaceForProp1)
(InterfaceForProp1).SetProp1(Prop1);
if(item is InterfaceForProp2)
(InterfaceForProp2).SetProp2(Prop2);
if(item is InterfaceForProp3)
(InterfaceForProp3).SetProp3(Prop3);
你可以像这样创建一个类:
public class MyClassUsesProp2And3 : InterfaceForProp2, InterfaceForProp3
但是,我担心这段代码过于分散,它可能会膨胀太多。也许我不应该太害怕本质上是一种方法接口,但我想在走这条路之前看看我是否缺少设计模式? (唯一出现在我脑海中但不太合适的是Decorator 或Composite 模式)
更新
所有属性都是唯一类型。
最终,这是依赖注入的一种形式。代码太乱了,现在不能使用像 Ninject 这样的东西,但最终我什至可以摆脱其中的一些并使用注入容器。除了设置变量之外,目前还有一些逻辑正在完成。这都是遗留代码,我只是想一点一点地清理它。
【问题讨论】:
-
Prop1、Prop2 和 Prop3 是同一类型吗?因为我几乎认为您想要一个具有 SetProp() 方法的 InterfaceForProp1、InterfaceForProp2 和 InterfaceForProp3 的超类,该方法接受 Prop1、Prop2 和 Prop3 的任何类型的参数。
-
也许 Prop1、Prop2 和 Prop3 是尚未由对象表示的域概念的属性。这可能会简化您的界面。
-
@dmn 我刚刚更新了我的问题,并补充说所有类型都不同。如果它们都一样,那么这将是蛋糕。
标签: design-patterns interface strategy-pattern