我希望你能帮助我解决我的问题:
我有一堂课打肥皂。但是,如果肥皂定义发生变化,我将不得不编写一个新类或从中继承等。
因此,我来到解决方案中来写这样的东西:
switch(version)
{
case "1.0":
saopV1.getData()
case "2.0":
soapV2.getData()
}
我知道,代码很糟糕。然后我读到了战略模式,然后我想,哇,这是我要摆脱这种糟糕的开关情况的东西:
abstract SoapVersion
{
public SoapVersion GetSoapVersion(string version)
{
//Damn switch-case thing
//with return new SoapV1() and return new SoapV2()
}
public string[] virtual getData()
{
//Basic Implementation
}
}
class SoapV1:SoapVersion
{
public override string[] getData()
{
//Detail Implementation
}
}
class SoapV2:SoapVersion
{//the same like soapv1}
但是我无法避免在代码中使用“ ifs”或切换大小写。使用OO技术是否有可能?
编辑:
GetSoapVersion-Function应该是静态的
最佳答案
这或多或少是一种以美丽的方式完成此操作的正确方法。
在代码的某个时刻,您必须决定是否必须使用v1或v2,因此无论如何您都必须具有条件语句(if或switch)。但是,在使用策略和工厂(工厂方法或工厂类)时,您已经集中了该决策。
我可以将抽象类上的工厂方法设为静态。
另外,我将利用模板方法模式:即,公共的,不可重写的GetData方法,该方法调用受保护的虚拟(抽象)方法,该方法应在具体实现中重写。
public abstract class SoapProcessor
{
protected SoapProcessor() { /* protected constructor since public is of no use */ }
public static SoapProcessor Create( SoapVersion version )
{
switch( version )
{
case SoapVersion.Version1 : return new SoapV1Processor();
case SoapVersion.Version2 : return new SoapV2Processor();
default: throw new NOtSupportedException();
}
}
public string[] GetData()
{
return GetDataCore();
}
protected abstract GetDataCore();
}
}