我有许多在不同的第三方系统上调用的方法。现在,我有另一个第三方系统,该系统将具有相同的一组方法。如果两个第三方系统都连接了,我将依次调用每个对象上的方法。
目前,我有一个可以绕过该类的类,可以调用一次该方法,然后检查该方法,然后在启用的每个系统上对其进行调用,该类具有每个对象类的实例,类似于此:
public class AACSCaller
{
3rdPartySystem1 _system1;
3rdPartySystem2 _system2;
public AACSCaller(Settings appSettings)
{
_appSettings = appSettings;
if (appSettings.system1Enabled)
{
_system1 = new 3rdPartySystem1();
}
if (appSettings.system2Enabled)
{
_system2 = new 3rdPartySystem2();
}
}
public void Method1()
{
if (appSettings.system1Enabled)
{
_system1.Method1();
}
if (appSettings.system2Enabled)
{
_system2.Method1();
}
}
public void Method2()
{
if (appSettings.system1Enabled)
{
_system1.Method2();
}
if (appSettings.system2Enabled)
{
_system2.Method2();
}
}
}
这是明智的做法,因为似乎确实存在更好的方法,而且我可能会在某个时候连接其他系统。
答案 0 :(得分:1)
这里可能的解决方案是为3rdPartySystem1
和3rdPartySystem2
类定义接口或基类,将实例存储在集合中,并为集合中的每个项目调用所需的方法。如果仅启用了一个系统,则集合中将只有一个项目;如果同时启用了两个系统,则将一个接一个地循环调用它们
public interface IThirdPartySystem
{
void Method1();
void Method2();
}
public class ThirdPartySystem1 : IThirdPartySystem
{
//implementation
}
public class ThirdPartySystem2 : IThirdPartySystem
{
//implementation
}
public class AACSCaller
{
IList<IThirdPartySystem> _systems = new List<IThirdPartySystem>();
public AACSCaller(Settings appSettings)
{
_appSettings = appSettings;
if (appSettings.system1Enabled)
{
_systems.Add(new ThirdPartySystem1());
}
if (appSettings.system2Enabled)
{
_systems.Add(new ThirdPartySystem2());
}
}
public void Method1()
{
foreach (var system in _systems)
system.Method1();
}
public void Method2()
{
foreach (var system in _systems)
system.Method2();
}
}
答案 1 :(得分:1)
我建议您使用具有Method1
和Method2
方法的接口,然后创建实现该接口的类System1
和System2
。在创建AACSCaller的地方,您可以初始化接口的正确实现,并在您的方法中仅调用无条件的正确实例方法。
public class AACSCaller
{
IThirdPartySystem ThirdPartySystem;
public AACSCaller(Settings appSettings)
{
_appSettings = appSettings;
ThirdPartySystem = appSettings.system1Enabled ? new ThirdPartySystem1() : new ThirdPartySystem2();
}
public void Method1() => ThirdPartySystem.Method1();
public void Method2() => ThirdPartySystem.Method2();
}
public interface IThirdPartySystem
{
void Method1();
void Method2();
}
public class ThirdPartySystem1 : IThirdPartySystem
{
public void Method1()
{
//code here..
}
public void Method2()
{
//code here..
}
}
public class ThirdPartySystem2 : IThirdPartySystem
{
public void Method1()
{
//code here..
}
public void Method2()
{
//code here..
}
}