擷取 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(); } } }結果
沒有留言:
張貼留言