以暗号翻译为例:
- UML图:
- 代码实现:
public class Context
{
public string HandleText { get; set; }
}
public abstract class BaseTextHandle
{
protected Dictionary<char, string> _ruleDic = new Dictionary<char, string>();
public virtual void Conversion(Context context)
{
if (string.IsNullOrWhiteSpace(context.HandleText))
return;
var newStrings = new List<string>();
foreach (var item in context.HandleText.ToLower().ToArray())
{
if (_ruleDic.ContainsKey(item))
{
newStrings.Add(_ruleDic[item]);
}
else
{
newStrings.Add(item.ToString());
}
}
context.HandleText = string.Join("", newStrings);
}
}
public class FirstTextHandle : BaseTextHandle
{
public FirstTextHandle()
{
var _Dictionary = new Dictionary<char, string>
{
{ 'a', "1" },
{ 'b', "2" },
{ 'c', "3" },
{ 'd', "4" },
{ 'e', "5" },
{ 'f', "6" },
{ 'g', "7" },
{ 'h', "8" },
{ 'i', "9" }
};
base._ruleDic = _Dictionary;
}
}
public class SecondTextHandle : BaseTextHandle
{
public SecondTextHandle()
{
var ruleDic = new Dictionary<char, string>
{
{ '1', "1" },
{ '2', "2" },
{ '3', "3" },
{ '4', "4" },
{ '5', "5" },
{ '6', "6" },
{ '7', "7" },
{ '8', "8" },
{ '9', "9" }
};
base._ruleDic = ruleDic;
}
}
public class LastTextHandle : BaseTextHandle
{
public override void Conversion(Context context)
{
if (context.HandleText.Contains("深夜代码"))
{
context.HandleText = "这是一个不错的人";
}
}
}
- 调用端代码:
class Program
{
static void Main(string[] args)
{
{
var context = new Context
{
HandleText = "ismdsdsfgjsdgl21424982sdg"
};
var handles = new List<BaseTextHandle>
{
{new FirstTextHandle() },
{new SecondTextHandle() },
{new LastTextHandle() },
};
foreach (var item in handles)
{
item.Conversion(context);
}
Console.WriteLine(context.HandleText);
}
{
var context = new Context
{
HandleText = "ismdsdsfgjsdgl深夜代码24982sdg"
};
var handles = new List<BaseTextHandle>
{
{new FirstTextHandle() },
{new SecondTextHandle() },
{new LastTextHandle() },
};
foreach (var item in handles)
{
item.Conversion(context);
}
Console.WriteLine(context.HandleText);
}
Console.ReadLine();
}
}
- 运行效果:
- 总结
解释器模式,给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。
代码下载地址:https://pan.baidu.com/s/1Odww0OuG1fvaVMTV_nT1Tw aj1g