我正在尋找利用.net應用程序的策略模式。我正在簡化代碼,但想法是一樣的。有一個交通接口,它將有兩個具體的類,摩托車,這兩個唯一的要求是實施可驅動的方法。爲了實現它,我想使用戰略模式和IDriveableStrategy接口,該接口將採用實現ITransport的類並使用該類中的信息來確定ITransport是否可驅動。我看到一些帖子質疑將背景發送給戰略的做法,但我現在想忽略這種辯論。如果我實現一個名爲MotorcycleDriveableStrategy的類,我想將其用作Motorcycle類的一個策略。採取其他接口的策略模式方法
在下面的代碼中,您會注意到我有兩個特定於Motorcycle類的附加屬性,我想用它來評估ITransport是否可驅動。在MotorcycleDriveableStrategy中,我已經註釋了理想情況下如何實現類,(因爲摩托車確實實現了ITransport,所以isDriveable實現了接口,但是當我嘗試這個時,我收到了一個編譯錯誤,所以我必須讓方法期待ITransport接口。
我能做到這一點,我想通過使IDriveableStrategy接口需要一個通用的實現ITransport
IDriveableStrategy<T> where T : ITransport
,並宣佈
MotorcycleDriveableStrategy<Motorcycle>
耦合,但我想知道如果我錯過了更大的圖片。泛型之前這將如何實現?戰略模式應該總是基於暴露的接口實現來評估上下文嗎?策略界面是否應該將界面作爲參數?有沒有另一種方法來實現這一點,而不添加numWheels到ITransport接口或使IDriveableStrategy通用?提前感謝您的任何建議或見解。
public interface ITransport
{
boolean driveable();
}
public class Car : ITransport
{
private driveableStrategy {get;set;}
public boolean driveable()
{
return driveableStrategy.isDriveable();
}
}
public class Motorcycle: ITransport
{
private driveableStrategy {get;set;}
private int numWheels {get;set;}
private string weatherExceptions {get;set;}
public Motorcycle(IDriveableStrategy driveableStrategy,int numWheels,string weatherExceptions)
{
this.driveableStrategy = driveableStrategy;
this.numWheels = numWheels;
this.weatherExceptions = weatherExceptions;
}
public boolean driveable()
{
return driveableStrategy.isDriveable();
}
}
public interface IDriveableStrategy
{
boolean isDriveable(ITransport transport);
}
public class MotorcycleDriveableStrategy
{
//What i would like to do
/*public boolean isDriveable(Motorcycle transport)
{
return transport.numWheels > 2;
}
*/
public boolean isDriveable(ITransport transport)
{
}
}