Last active
December 26, 2015 17:49
-
-
Save yemrekeskin/7189229 to your computer and use it in GitHub Desktop.
Implementation of the Interpreter design pattern in c#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Context | |
| { | |
| public string Value { get; set; } | |
| public int DigitalValue { get; set; } | |
| public Context(string Value) | |
| { | |
| this.Value = Value; | |
| } | |
| } | |
| public abstract class BaseExpression | |
| :IExpression | |
| { | |
| public abstract void Interpret(Context context); | |
| } | |
| public interface IExpression | |
| { | |
| void Interpret(Context context); | |
| } | |
| public class CharExpression | |
| : BaseExpression | |
| { | |
| public Context Context; | |
| Char Character; | |
| public CharExpression(Char ch) | |
| { | |
| this.Character = ch; | |
| } | |
| public override void Interpret(Context context) | |
| { | |
| this.Context = context; | |
| this.Context.DigitalValue += GetCharCode(Character); | |
| } | |
| private int GetCharCode(char character) | |
| { | |
| UTF32Encoding encoding = new UTF32Encoding(); | |
| byte[] bytes = encoding.GetBytes(character.ToString().ToCharArray()); | |
| return BitConverter.ToInt32(bytes, 0); | |
| } | |
| } | |
| //public enum Letters | |
| //{ | |
| // A, B, C, Ç, D, E, F, G, Ğ, H, I, İ, J, K, L, M, N, O, Ö, P, R, S, Ş, T, U, Ü, V, Y, Z, | |
| // a, b, c, ç, d, e, f, g, ğ, h, ı, i, j, k, l, m, n, o, ö, p, r, s, ş, t, u, ü, v, y, z | |
| //} | |
| public static class Letters | |
| { | |
| public static List<Char> GetLetters() | |
| { | |
| var letters = Enumerable.Range(0, 255).Select(Convert.ToChar).Where(Char.IsLetter).ToList<Char>(); | |
| return letters; | |
| } | |
| } | |
| public interface IParser | |
| { | |
| void Parser(); | |
| } | |
| public abstract class BaseParser | |
| : IParser | |
| { | |
| public abstract void Parser(); | |
| } | |
| public class HexParser | |
| : BaseParser | |
| { | |
| private List<BaseExpression> tokenList = new List<BaseExpression>(); | |
| public Context Context; | |
| public HexParser(Context ctxt) | |
| { | |
| this.Context = ctxt; | |
| } | |
| public override void Parser() | |
| { | |
| foreach (Char ch in Context.Value.ToCharArray()) | |
| tokenList.Add(new CharExpression(ch)); | |
| // Interpret | |
| foreach (IExpression exp in tokenList) | |
| exp.Interpret(Context); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment