我有很多方法(在这种情况下,来自网络服务,但也许这没有影响?)可以调用。它们已经是固定发布版本并且不会更改,由我来适应它们。我的项目已经有了代理,事实上,我已经调用了它们并且项目没问题。
该类main方法获取一些输入参数(交易类型,以及包含交易数据的XML字符串)。基于 TransactionType,我知道我应该调用哪个类和方法。我还必须为它提供一个它期望的类型变量,该变量已经根据提供的 XML 构建。这是今天的样子(我这里没有代码,所以请原谅我的任何语法错误),大约:
public class MyClass ()
{
public void MyMethod( string TransactionType, string XML )
{
switch( TransactionType ) {
case "1":
type1VO type1Object = ( new Deserializer<Type1>() ).XML2Object( XML );
ws = new WSProxy1();
string response = ws.Method1( type1VO );
//
// lots of other lines of code that use type1VO, type1Object, the response, etc.
//
break;
case "2":
type2VO type2Object = ( new Deserializer<Type2>() ).XML2Object( XML );
ws = new WSProxy2();
string response = ws.Method2( type2VO );
//
// same structure here, but handling types specific for "case 2"
//
break;
}
...
}
}
它一直在继续。今天,这段代码已经在运行,处理大约 15 种不同的交易类型,但它是按照您在上面看到的方式开发的。当我要更改它时(将把这段代码移动到它自己的库中,因为其他系统需要这种逻辑),我认为它可以从一些代码改进中获益。此外,上面的代码也大大减少了:有更多行处理每种情况的特定类型,我只是举了一个例子。
因为它在工作,所以我并不那么担心,但它对我来说似乎并不那么“优雅”。给我的印象是某种设计模式可以处理这个问题,而且我可以用一个 block 处理任何交易,而不是为每种交易类型重复它。也许我错了,这无法完成,我只是通过查看重复代码“感觉”它可以。
它是.NET v2.0 上的C#,但我不介意是否有涉及其他版本或语言的答案。我更关心所涉及的概念。感谢大家提供的任何提示,它们总是很棒。
最佳答案
您可以尝试 Adapter Pattern 的组合和 Strategy Pattern .
创建一个调用方法的接口(interface),并为支持此接口(interface)的每个代理编写适配器。适配器应该封装任何特定于它正在适配的对象的行为。您还可以让接口(interface)返回它们支持的事务类型,以便在运行时启用切换。
一个例子可能是:
public interface IExecuteStrategy
{
string TransactionType {get;}
void Execute( string xmlData );
}
public class WsProxy1Adapter : IExecuteStrategy
{
public string TransactionType
{
get { return "1"; }
}
public void Execute(string xmlData)
{
Type1 type1Object = ( new Deserializer<Type1>() ).XML2Object( XML );
var ws = new WSProxy1();
string response = ws.Method1( type1Object );
//
// lots of other lines of code that use type1VO, type1Object, the response, etc.
//
}
}
public class WsProxy2Adapter : IExecuteStrategy
{
public string TransactionType
{
get { return "2"; }
}
public void Execute(string xmlData)
{
Type2 type2Object = ( new Deserializer<Type2>() ).XML2Object( XML );
var ws = new WSProxy2();
string response = ws.Method1( type2Object );
//
// lots of other lines of code that use type1VO, type1Object, the response, etc.
//
}
}
public class MyClass
{
private static Dictionary<string, IExecuteStrategy> _transactionHandlers;
static MyClass()
{
_transactionHandlers = new Dictionary<string,IExecuteStrategy>();
IExecuteStrategy obj = new WsProxy1Adapter();
_transactionHandlers.Add(obj.TransactionType, obj);
obj = new WsProxy2Adapter();
_transactionHandlers.Add(obj.TransactionType, obj);
}
public void MyMethod( string TransactionType, string XML )
{
_transactionHandlers[TransactionType].Execute( XML );
}
}
关于c# - 我可以调用执行相似功能的不同类(具有不同的方法和类型)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4900009/