星期二, 4月 07, 2015

[DP] 轉接器模式

根據 Head First Design Pattern 書本內容,來練習轉接器模式

擷取 Head First 上的類別圖

[DP]轉接器模式-0


Project 內容

[DP]轉接器模式-1

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]轉接器模式-2

沒有留言:

張貼留言