Template Pattern (8)

模板模式:

       定义一个算法的几本框架和操作步骤,在其派生类中具体实现算法实现步骤的细节,派生类不改变算法的结构。

using System;

using System.Text;

using System.IO;

 

namespace Hello

{

   public abstract class CaffeineBeverageWithHook

   {

      public void PrepareRecipe()

      {

        BoilWater();

        Brew();

        PourInCup();

        if (CustomerWantsCondiments())

        {

           AddCondiments();

        }

      }

      public abstract void Brew();

      public abstract void AddCondiments();

      void BoilWater()

      {

        Console.WriteLine("Boiling Watter...");

      }

      void PourInCup()

      {

        Console.WriteLine("Pouring into cup...");

      }

      public virtual bool CustomerWantsCondiments()

      {

        return true;

      }

   }

   public class CoffeeWithHook : CaffeineBeverageWithHook

   {

      public override void Brew()

      {

        Console.WriteLine("Dripping Coffee through filter...");

      }

      public override void AddCondiments()

      {

        Console.WriteLine("Adding Sugar and Milk...");

      }

      public override bool CustomerWantsCondiments()

      {

        Console.WriteLine("Would you like sugar and milk?(y/n)");

        string answer = Console.ReadLine();

        if (answer.ToLower().ToString() == "y")

        {

           return true;

        }

        else

        {

           return false;

        }

      }

   }

   public class TeaWithHook : CaffeineBeverageWithHook

   {

      public override void Brew()

      {

        Console.WriteLine("Dripping Tea through filter...");

      }

      public override void AddCondiments()

      {

        Console.WriteLine("Adding Sugar and Milk...");

      }

      public override bool CustomerWantsCondiments()

      {

        Console.WriteLine("Would you like sugar and milk?(y/n)");

        string answer = Console.ReadLine();

        if (answer.ToLower().ToString() == "y")

        {

           return true;

        }

        else

        {

           return false;

        }

      }

   }

 

   class Program

   {

      static void Main(string[] args)

      {

        CoffeeWithHook coffee = new CoffeeWithHook();

        coffee.PrepareRecipe();

 

        TeaWithHook tea = new TeaWithHook();

        tea.PrepareRecipe();

      }

   }

}

 

posted @ 2011-10-04 22:24  Erebus_NET  阅读(94)  评论(0编辑  收藏  举报