Design
Pattern : Bridge
Bridge的定義是:將抽象與實作解耦合,讓兩者可以獨立變化。
Bridge的定義是:將抽象與實作解耦合,讓兩者可以獨立變化。
需求:
將原本車子的駕駛方法改為手動駕駛。
1.
既有的Interface和Class
public interface ICar
{
DPLib.Color Color { get; set; }
String Name { get; set; }
void Drive();
}
public class Focus : ICar
{
// …省略實作ICar的程式碼
public void Drive()
{
Console.WriteLine("I am driving {0} {1} ({2})", color.ToString(), name, BRAND);
}
}
public interface ICar
{
DPLib.Color Color { get; set; }
String Name { get; set; }
void Drive();
}
public class Focus : ICar
{
// …省略實作ICar的程式碼
public void Drive()
{
Console.WriteLine("I am driving {0} {1} ({2})", color.ToString(), name, BRAND);
}
}
2. 如果是用繼承的方式,會需要新增每一個實作ICar的類別,所以我們在這邊使用Bridge的方式。
public interface IAutoCar
{
ICar Car { get; set; }
void Drive(bool IsAuto);
}
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 interface IAutoCar
{
ICar Car { get; set; }
void Drive(bool IsAuto);
}
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();
}
}
}
u
FocusBridge實作IAutoCar,而IAutoCar作必須定義在design-time可以建立的ICar物件。
3.
主程式
IAutoCar myCar2 = new FocusBridge();
myCar2.Car = new Focus();
myCar2.Drive(true);
myCar2.Drive(false);
結果:
Black Focus 自動駕駛中
I am driving Black Focus(FORD)
IAutoCar myCar2 = new FocusBridge();
myCar2.Car = new Focus();
myCar2.Drive(true);
myCar2.Drive(false);
結果:
Black Focus 自動駕駛中
I am driving Black Focus(FORD)
沒有留言:
張貼留言