行,所以我在尋找一個一些代碼,看起來大致是這樣的:尋找一種設計模式,以取代huuuge如果對象類型
void DoSomething(object o)
{
if (o is Sometype1) {
//cast o to Sometype and do something to it
}
else if (o is Sometype2) {
//cast o to Sometype2 and do something to it
}
...
else if (o is SometypeN) {
//cast o to SometypeN and do something to it
}
}
現在,一個辦法是讓所有的物品o
是作爲參數,可以實現一個接口一樣
interface ICanHaveSomethingDoneToMe
{
//expose various properties that the DoSomething method wants to access
}
但這樣做的問題是,我不希望我的所有對象實現這個接口 - 在做一些方法並沒有真正與他們所屬的邏輯。我應該用什麼模式來處理這個問題?
我懷疑類似的
interface IPropertiesForDoingSomethingTo<T>
{
//expose various properties that the DoSomething method wants to access
}
一系列的實現可能會更好。我想爲每個對象類型實現一個實現,但我有這個新問題。我會在這點上需要有一個方法,如
IPropertiesForDoingSomethingTo<T> GetPropsGeneric(T t);
但這是需要有一個大規模的開關呢?我應該定義與方法負載一類像
IPropertiesForDoingSomethingTo<Someobject1> GetProps(Someobject1 t);
...
IPropertiesForDoingSomethingTo<Someobject1> GetProps(SomeobjectN t);
這相比於普通版本,您將無法在運行時添加新類型的問題。有沒有什麼狡猾的人可以用GetPropsGeneric中的DI容器來解決容器問題?謝謝!
你可以在任何你不能改變的類上實現一個包裝,並讓它實現你的接口。然後只處理已包裝的對象。例如,我使用DataContext執行此操作,以便於進行單元測試。 – tvanfosson 2008-11-20 18:00:30