我們假設我有這種情況:我有兩個信息庫,並且我想要訪問這兩個信息庫,但是最好離開決定使用哪個回購的任務到普通類。如何編寫一個好的離線在線調度程序
目標是與類似到我下面寫的代碼的東西做到這一點,但是這聽起來很糟糕:
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'**。如果需要,可以運行該示例,代碼已準備好用於控制檯應用程序。 –