我们假设我有这种情况:我有两个信息库,并且我想要访问这两个信息库,但是最好离开决定使用哪个回购的任务到普通类。如何编写一个好的离线在线调度程序
目标是与类似到我下面写的代码的东西做到这一点,但是这听起来很糟糕:
where TOnline : class
where TOffline : class
where TContract : class
相信我能ommit这一点,但bassically就是我要问是为了停止使用反射和去键入。也许任何设计模式 recomendation?
代码(如果你复制/粘贴在一个控制台应用程序替换Program
类,你应该能够运行示例)
using CustomerDispatcher = DispatcherProxy<CustomerOnline, CustomerOffline, ICustomer>;
public interface ICustomer
{
string Get(int id);
}
public class CustomerOnline : ICustomer
{
public string Get(int id)
{
// Get From intranet DB
return "From DB";
}
}
public class CustomerOffline : ICustomer
{
public string Get(int id)
{
// Get From local storage
return "From local storage";
}
}
public class DispatcherProxy<TOnline, TOffline, TContract>
where TOnline : class
where TOffline : class
where TContract : class
{
public TContract Instance { get; set; }
public bool IsConnected { get; set; }
public DispatcherProxy()
{
// Asume that I check if it's connected or not
if (this.IsConnected)
this.Instance = (TContract)Activator.CreateInstance(typeof(TOnline));
else
this.Instance = (TContract)Activator.CreateInstance(typeof(TOffline));
}
}
class Program
{
static void Main(string[] args)
{
var customerDispatcher = new CustomerDispatcher();
Console.WriteLine("Result: " + customerDispatcher.Instance.Get(1));
Console.Read();
}
}
提前感谢!
嗯..不会编译。 –
什么是错误? –
**不能将类型'TOFFLINE'隐式转换为'TContract'**。如果需要,可以运行该示例,代码已准备好用于控制台应用程序。 –