Design
Pattern : Strategy
Strategy的定義:
1.
原本的程式碼中,在FocusBridge 實作 IAutoCar的Drive方法的時候,我們用了一個布林值去判斷目前是要做手動還是自動駕駛。 接下來我們要用Strategy修改這部分。
原來的程式:
public class FocusBridge : IAutoCar
{
private ICar car;
ICar IAutoCar.Car
{
get {return this.car; }
set { this.car = value; }
}
void IAutoCar.Drive(bool IsAuto)
{
if(IsAuto == true)
{
Console.WriteLine(
String.Format("{0} {1} 自動駕駛中",
this.car.Color.ToString(), this.car.Name));
}
else
{
this.car.Drive();
}
}
}
原來的程式:
public class FocusBridge : IAutoCar
{
private ICar car;
ICar IAutoCar.Car
{
get {return this.car; }
set { this.car = value; }
}
void IAutoCar.Drive(bool IsAuto)
{
if(IsAuto == true)
{
Console.WriteLine(
String.Format("{0} {1} 自動駕駛中",
this.car.Color.ToString(), this.car.Name));
}
else
{
this.car.Drive();
}
}
}
2.
Strategy
: Interface
public interface IDriveStrategy
{
void Drive(ICar myCar);
}
public interface IDriveStrategy
{
void Drive(ICar myCar);
}
3.
Strategy
: 實作兩個或更多Class
public class Auto:IDriveStrategy
{
void IDriveStrategy.Drive(ICar myCar)
{
Console.WriteLine(
String.Format("{0} {1} 自動駕駛中",
myCar.Color.ToString(),myCar.Name));
}
}
public class Manual:IDriveStrategy
{
void IDriveStrategy.Drive(ICar myCar)
{
Console.WriteLine(
String.Format("{0} {1} 手動駕駛中",
myCar.Color.ToString(),myCar.Name));
}
}
public class Auto:IDriveStrategy
{
void IDriveStrategy.Drive(ICar myCar)
{
Console.WriteLine(
String.Format("{0} {1} 自動駕駛中",
myCar.Color.ToString(),myCar.Name));
}
}
public class Manual:IDriveStrategy
{
void IDriveStrategy.Drive(ICar myCar)
{
Console.WriteLine(
String.Format("{0} {1} 手動駕駛中",
myCar.Color.ToString(),myCar.Name));
}
}
4.
主程式
IAutoCar myCar = new FocusBridge();
myCar.Car = new Focus();
IDriveStrategy driveStrategy = new Manual();
myCar.Drive(driveStrategy);
結果:
Black Focus 手動駕駛中
IAutoCar myCar = new FocusBridge();
myCar.Car = new Focus();
IDriveStrategy driveStrategy = new Manual();
myCar.Drive(driveStrategy);
結果:
Black Focus 手動駕駛中
沒有留言:
張貼留言