擷取 Head First 上的類別圖
Project 內容
Duck 相關
namespace DP_Adapter
{
public interface IDuck
{
void quack();
void fly();
}
}
namespace DP_Adapter
{
public class MallardDuck : IDuck
{
public void quack()
{
Console.WriteLine("Quack");
}
public void fly()
{
Console.WriteLine("I'm flying");
}
}
}
Turkey 相關
namespace DP_Adapter
{
public interface ITurkey
{
void gobble();
void fly();
}
}
namespace DP_Adapter
{
public class WildTurkey : ITurkey
{
public void gobble()
{
Console.WriteLine("Goole gobble");
}
public void fly()
{
Console.WriteLine("I'm flying a short distance");
}
}
}
TurkeyAdapter
namespace DP_Adapter
{
public class TurkeyAdapter : IDuck
{
private ITurkey _Turkey;
public TurkeyAdapter(ITurkey Turkey)
{
this._Turkey = Turkey;
}
public void quack()
{
this._Turkey.gobble();
}
public void fly()
{
for (int i = 0; i < 5; i++)
{
this._Turkey.fly();
}
}
}
}
執行 namespace DP_Adapter
{
class Program
{
static void Main(string[] args)
{
MallardDuck duck = new MallardDuck();
WildTurkey turkey = new WildTurkey();
IDuck turkeyAdapter = new TurkeyAdapter(turkey);
Console.WriteLine("The Turkey says...");
turkey.gobble();
turkey.fly();
Console.WriteLine("\nThe Duck says...");
testDuck(duck);
Console.WriteLine("\nThe TurkeyAdapter says...");
testDuck(turkeyAdapter);
}
public static void testDuck(IDuck duck)
{
duck.quack();
duck.fly();
}
}
}
結果 ![[DP]轉接器模式-0](https://farm8.staticflickr.com/7720/16872942148_66a7f2b374_z.jpg)
![[DP]轉接器模式-1](https://farm8.staticflickr.com/7605/16854569130_2785db1241_o.jpg)
![[DP]轉接器模式-2](https://farm8.staticflickr.com/7637/17042101665_22de2f4251_o.jpg)
沒有留言:
張貼留言