重构是基本方法的运算符
我有一些接口 ISome1, ISome2 .. ISomeX
我有可以从其中一些接口继承的类
class SomeModel1 : ISome1 , ISome2
{
// specific properties
}
class SomeModel2 : ISome3 , ISome12
{
// specific properties
}
class SomeModelX : ISomeXX , ISomeXXX
{
// specific properties
}
我有一个基于该接口执行某些操作的类有一个对象
public void InitSomeModelProperty(SomeModel model)
{
if (model is ISome1)
{
var isomeAcation = new SomeAcation();
isomeAcation.InitProps(model);
}
if (model is ISome2)
{
var isomeAcation2 = new SomeAcation2();
isomeAcation2.InitProps(model);
}
// it is a dozen of logic like this
if (model is ISomeX)
{
var isomeAcationX = new SomeAcationX();
isomeAcationX.InitProps(model);
}
}
如何正确减少数量如果(模型是ISome1)?
I have some interfaces ISome1, ISome2 .. ISomeX
I have classes that could be inherited from some of these interfaces
class SomeModel1 : ISome1 , ISome2
{
// specific properties
}
class SomeModel2 : ISome3 , ISome12
{
// specific properties
}
class SomeModelX : ISomeXX , ISomeXXX
{
// specific properties
}
I have a class that do some action based on that interfaces has an object
public void InitSomeModelProperty(SomeModel model)
{
if (model is ISome1)
{
var isomeAcation = new SomeAcation();
isomeAcation.InitProps(model);
}
if (model is ISome2)
{
var isomeAcation2 = new SomeAcation2();
isomeAcation2.InitProps(model);
}
// it is a dozen of logic like this
if (model is ISomeX)
{
var isomeAcationX = new SomeAcationX();
isomeAcationX.InitProps(model);
}
}
how to correct reduce the amount if (model is ISome1) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种选择是将操作可以处理哪些类型的知识转移到操作本身中。例如:
Then:
InitSomeModelProperty
then 不需要了解哪些操作采用哪些类型——该知识由操作本身持有。InitSomeModelProperty
只需要迭代所有可能的操作:我已经明确地写出了这一点,但是您可以将它们全部放入一个集合中,例如(这就是为什么我引入了非泛型 <代码>ActionBase)。如果您需要为每个模型创建一个新的操作实例,那么您可能需要为每个操作创建一个工厂,并且该工厂决定是否为给定模型实例化其相应的操作。
One option is to move the knowledge of what types an action can handle into the action itself. E.g.:
Then:
InitSomeModelProperty
then doesn't need knowledge of which actions take which types -- that knowledge is held by the action itself.InitSomeModelProperty
just needs to iterate through all of the possible actions: I've written this out explicitly, but you could put them all in a collection, for example (which is why I introduced the non-genericActionBase
).If you need to have a new action instance for each model, then you'll probably want a factory for each action, and the factory decides whether to instantiate its corresponding action for a given model.