设计模式---翻译器模式

来源:互联网 发布:linux pptp server 编辑:程序博客网 时间:2024/05/17 07:41
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace ConsoleApplication1
  5. {
  6.     abstract class Expretion
  7.     {
  8.         public void Translate(Words w)
  9.         {
  10.             string s = w.MyWords.Substring(0, 1);
  11.             w.MyWords = w.MyWords.Substring(2);
  12.             Excute(s);
  13.         }
  14.         public abstract void Excute(string s);
  15.     }
  16.     class EnglishExpretion:Expretion
  17.     {
  18.         public override void Excute(string s)
  19.         {
  20.             switch (s)
  21.             {
  22.                 case "e":
  23.                     Console.WriteLine("对方说的英语");
  24.                 break;
  25.             }
  26.         }
  27.     }
  28.     class GermanExpretion:Expretion
  29.     {
  30.         public override void Excute(string s)
  31.         {
  32.             switch (s)
  33.             {
  34.                 case "g":
  35.                     Console.WriteLine("对方说的德语");
  36.                     break;
  37.             }
  38.         }
  39.     }
  40.     class Words
  41.     {
  42.         private string words;
  43.         public string MyWords
  44.         {
  45.             get
  46.             {
  47.                 return words;
  48.             }
  49.             set
  50.             {
  51.                 words = value;
  52.             }
  53.         }
  54.     }
  55.     class Client
  56.     {
  57.         public static void Main()
  58.         {
  59.             Words w = new Words();
  60.             w.MyWords = "e g e e g ";
  61.             Expretion e=null;
  62.             while (w.MyWords.Length>0)
  63.             {
  64.                 switch (w.MyWords.Substring(0,1))
  65.                 {
  66.                 case "e":
  67.                         e = new EnglishExpretion();
  68.                     break;
  69.                     case"g":
  70.                     e = new GermanExpretion();
  71.                     break;
  72.                 }
  73.                 e.Translate(w);
  74.             }
  75.             Console.Read();
  76.         }
  77.     }
  78. }

 

 

 

 

原创粉丝点击