2013年12月6日 星期五

Design Pattern : Interpreter

Design Pattern : Interpreter

Definition :
Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language



Original Context:原始翻譯前的內容
Interpreted Context:翻譯後的內容
IExpression:定義Interpret翻譯方法
ExpressionA & B
:實作Interpret翻譯方法

底下是將原本一長串的字串資料翻譯成Customer物件


1.  IExpression

public interface IExpression
{
 
Customer Interpret();
}

2.  Customer

public class Customer:IDisposable
{
   
public String Name { get; set; }
   
public int Age { get; set; }
   
public String PhoneNumber { get; set; }
   
public String Address { get; set; }
}

3.  ExpressionA

public class ExpressionA:IExpression
{
   
private String content = String.Empty;
   
public ExpressionA(String info)
    {
      
this.content = info;
    }
   
public Customer Interpret()
    {
      
using(Customer customer = new Customer())
       {
          customer.Name =
this.content.Substring(0, 5).Trim();
          customer.Age =
int.Parse(this.content.Substring(5, 3).Trim());
          customer.PhoneNumber =
this.content.Substring(8, 15).Trim();
          customer.Address =
this.content.Substring(22, 50).Trim();
         
return customer;
       }
    }
}

4.  主程式:
String name = "JB";
int age = 32;
String phoneNum = "0933-XXX-XXX";
String addr = "Taipei City, Neihui Street";

String info = String.Format("{0,-5}{1,3}{2,-15}{3,-50}", name, age.ToString(),phoneNum,addr);

Console.WriteLine("收到的原始資料:{0}", info);

IExpression exp = new ExpressionA(info);
Customer jb = exp.Interpret();

Console.WriteLine("姓名:{0}", jb.Name);
Console.WriteLine("年齡:{0}", jb.Age);
Console.WriteLine("電話號碼:{0}", jb.PhoneNumber);
Console.WriteLine("住址:{0}", jb.Address);

結果:
收到的原始資料:JB    320933-XXX-XXX   Taipei City, Neihui Street

姓名:JB
年齡:32
電話號碼:0933-XXX-XXX
住址:Taipei City, Neihui Street

=>
可以看到原本收到的是一串的資料,經過Interpreter之後,翻譯成一個可用的物件了。


5.  Reference

沒有留言:

張貼留言