我有以下用例,很多代码紧密耦合在一个具体类型(比如Concrete1).后来想通了具体的类型需要改变,所以定义了一个接口.例如
Class ABC {
virtual int foo() = 0;
virtual int getType() = 0;
}
class Concrete1 : public ABC {
int foo() {
... }
int getType() {
return 1;
}
}
class Concrete2 : public ABC {
int foo() {
... }
int getType() {
return 2;
}
}
Run Code Online (Sandbox Code Playgroud)
静态工厂模式用于创建对象.因此,创建对象new Concrete1的所有位置都将替换为ABCFactory :: createType().
现在代码中有很多地方我需要检查createType返回的对象是否是Concrete1或Concrete2并相应地执行相关逻辑(因此代码中有很多if else :()).
我希望在代码中避免使用很多if else作为此更改的一部分.有什么建议?
困扰我的事情是
if (abc.getType() == 1) {
...
} else if (abc.getType() ==2) {
...
}
Run Code Online (Sandbox Code Playgroud)
使用接口的全部意义在于您可以使用多态,这意味着您永远不必检查实例的类型.这样做是一个非常大的代码味道(见Fowlers Refacotring).将条件逻辑移动到具体类,并添加te函数,将其处理到接口
编辑(添加代码示例,因为最初的帖子是从手机完成的):
你正在努力:
void Main(string[] args)
{
Bird bird = BirdFactory.GetPigeon();
if (bird.GetType().Equals(typeof(Duck)))
{
Console.WriteLine("quack");
}
else if (bird.GetType().Equals(typeof(Pigeon)))
{
Console.WriteLine("coo coo");
}
}
Run Code Online (Sandbox Code Playgroud)
相反,尝试:
interface Bird
{
void Speak();
}
class Duck : Bird
{
void Speak()
{
Console.Write("quack");
}
}
class Pigeon : Bird
{
void Speak()
{
Console.Write("coo coo");
}
}
void Main(string[] args)
{
Bird bird = BirdFactory.GetPigeon();
bird.Speak();
}
Run Code Online (Sandbox Code Playgroud)