場景:大小寫數(shù)字互相轉(zhuǎn)換
創(chuàng)新互聯(lián)堅持“要么做到,要么別承諾”的工作理念,服務領域包括:網(wǎng)站設計制作、成都做網(wǎng)站、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣等服務,滿足客戶于互聯(lián)網(wǎng)時代的武威網(wǎng)站設計、移動媒體設計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡建設合作伙伴!
abstract class Expresstion
{
//解釋器
public void Interpret(PlayContext context)
{
string value = context.PlayText.Substring(0,1);
Translate(value);//處理當前字符
context.PlayText = context.PlayText.Substring(1); //去除已處理的字符
}
public abstract void Translate(string key);
}
class Upper : Expresstion
{
public override void Translate(string key)
{
string upper = "";
switch (key)
{
case "1":upper = "一";break;
case "2": upper = "二"; break;
case "3": upper = "三"; break;
case "4": upper = "四"; break;
case "5": upper = "五"; break;
case "6": upper = "六"; break;
case "7": upper = "七"; break;
case "8": upper = "八"; break;
case "9": upper = "九"; break;
case "0": upper = "零"; break;
}
Console.Write(upper);
}
}
class Lower : Expresstion
{
public override void Translate(string key)
{
string lower = "";
switch (key)
{
case "一": lower = "1"; break;
case "二": lower = "2"; break;
case "三": lower = "3"; break;
case "四": lower = "4"; break;
case "五": lower = "5"; break;
case "六": lower = "6"; break;
case "七": lower = "7"; break;
case "八": lower = "8"; break;
case "九": lower = "9"; break;
case "零": lower = "0"; break;
}
Console.Write(lower);
}
}
//上下文
class PlayContext
{
private string playText;
public string PlayText
{
get
{
return playText;
}
set
{
playText = value;
if (value.Length > 0)
{
Expresstion expresstion = null;
string values = playText.Substring(0, 1);
switch (values)
{
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
case "0": expresstion = new Upper(); break;
case "一":
case "二":
case "三":
case "四":
case "五":
case "六":
case "七":
case "八":
case "九":
case "零": expresstion = new Lower(); break;
}
expresstion.Interpret(this);
}
}
}
}
//前端
static void Main(string[] args)
{
PlayContext playContext = new PlayContext();
playContext.PlayText = "123四五六7八9零";
Console.ReadLine();
}
總結(jié):設定規(guī)則將當前語法轉(zhuǎn)變成另外一種語言。當一個語言需要解釋執(zhí)行,并且可將該語言中的句子表示為抽象語法樹的時候,可使用該模式。
好處:容易擴展文法規(guī)則,并且各個節(jié)點的規(guī)則類很容易編寫。
缺點:用了遞歸,效率要差、使用場景不多、規(guī)則多的時候難維護。