Interpreter Design Pattern
Selamlar;
Bugün behavior gurubuna ait belli bir düzendeki metinlerin sayısal veya mantıksal olarak işlenmesi gereken durumlarda kullanılan Interpreter design pattern hakkında konuşacağız. Belli bir düzendeki metinler üzerinde işlemden kasıt örnek olarak cryptolanmış metinler, binary’ye çevrilmiş ve convert edilmiş imagelara ait contentler üzerinden sıralı işlem yapılarak image de bozuk olan yerleri, değişen renk paletindeki büyük farktan algılanıp bu kısmın temizlenmesi, kelime ya da hece bazında shortlink haline getirilmiş url contentler, hatta yine binary’ye çevrilmiş wave dosylar içinde sıralı işlem yapılarak belli bir dalgadan yüksek ses bulunup bu bölüm silinerek sesteki gürültüden arındırma gibi farklı işlemlerdir. Daha bunun gibi birçok kural işletme motorlarına(Rule Engine) ihtiyaç duyulan durumlar vardır. Kısaca dofactory.com a göre kullanım oranı %20 civarında olmasına rağmen bireysel olarak çokça karşılaştığım durumdur.:)
Interpreter tasarım deseninde; bu özel ifadelerin işlenmesi için, hepsinin aynı interface veya abstract classtan türediği çeşitli operational classlar vardır. Herbir class’ın kendine özgü bir görevi vardır. Hepsi belirlenen rule’a göre düzenli ifade üzerinde işlem yaparak sonuca giderler. Aşşağıda uml diyagramı görünmektedir.
Yukarıda görüldüğü gibi bir işlem yapılacak context; client tarafından AbstractClass’a Interpret amacı yani düzenli metnin işlenmesi için gönderilir. TerminalExpression ile NonterminalExpression isimli iki farklı Exrepssion tipi bu AbstractClass’dan türetilmiştir. Terminal’dan kasıt belirlenen rule göre işletilen operationdır. Nonterminal ise, bazen iki terminal or veya and ile bağlanabilir. İşte bu durumlar Nonterminal tipler içerisinde değerlenidirilir. Ve her zaman işletilme önceliği Nonterminal tiplerdedir.
Bugünkü örneğimizde roma rakamlarını numeric değere convert ediceğiz. Ve sadece TerminalExpressionları kullanacağız..
Öncelikle bir WebApi projesi yaratılır.Ve WebApi’nin cross domain’de çalışması için Install-Package Microsoft.AspNet.WebApi.Cors’u Nuget’den indirilir. Ayrıca WebApiConfig içine config.EnableCors(); yazılır.
Ayrıca yaratılan InterpreterController classının üstüne [EnableCors(origins: “*”, headers: “*”, methods: “*”)] attribute’u eklenir. Tüm bu cross domain için config işlemleri bittikten sonra,
ilk olarak operation adında bir class yaratılır. İşlem yapılacak text’i ve dönen sayısal sonucu tutan Context class’ı aşşağıda görüldüğü gibidir.
Convert edilmesi için girilen roma rakamındaki string değer Formula yazılır. Convert edilecek sayısal değer NumberValue‘ye karşılık gelmektedir.
Context.cs:
1 2 3 4 5 |
public class Context { public string Formula { get; set; } public int NumberValue { get; set; } } |
TerminaExpression classlarının yani her bir karaktere karşılık gelen sayısal değerin hesaplandığı classların türetildiği abstract classlar aşşağıda RoleExpress adında tanımlanmıştır. Tüm Expression classlar Interpret işlemi yaparak, roma rakamını ait olduğu sayısal değere çevirip gerekli işlemleri yaparlar.
RoleExpression:
1 2 3 4 |
abstract class RoleExpression { public abstract void Interpret(Context context); } |
ThousendExpression.cs: ‘M’ karakterinin sayısal karşılığı 1000’dir Context’in NumberValue değeri bu işlemle 1000 arttırılır.
1 2 3 4 5 6 7 8 |
class ThousendExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('M')) context.NumberValue += 1000; } } |
FiveHunderdExpression.cs & FiveHunderdMinuesExpression.cs : Burada iki class tanımlanmıştır. Bir ‘D’ karakterine karşılık 500 eklenir. Diğeri 500 çıkarır. Amaç küçük sayı büyük sayının solunda ise çıkarılır. Sağında ise toplanır. Bu iki durum için tüm RoleExpress classlar aşşağıdaki gibi tanımlanır.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class FiveHunderdExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('D')) context.NumberValue += 500; } } class FiveHunderdMinuesExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('D')) context.NumberValue -= 500; } } |
HunderdExpression.cs & HunderdMinuesExpression.cs : ‘C’ karakteri için 100 değeri duruma göre ya eklenir yada çıkarılır.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class HunderdExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('C')) context.NumberValue += 100; } } class HunderdMinuesExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('C')) context.NumberValue -= 100; } } |
FiftyExpression.cs & FiftyMinuesExpression.cs: ‘L’ karakteri için 50 değeri duruma göre ya eklenir yada çıkarılır.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class FiftyExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('L')) context.NumberValue += 50; } } class FiftyMinuesExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('L')) context.NumberValue -= 50; } } |
TenExpression.cs & TenMinuesExpression .cs : ‘X’ karakteri için 10 değeri duruma göre ya eklenir yada çıkarılır.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class TenExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('X')) context.NumberValue += 10; } } class TenMinuesExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('X')) context.NumberValue -= 10; } } |
FiveExpression.cs & FiveMinuesExpression .cs : ‘V’ karakteri için 5 değeri duruma göre ya eklenir yada çıkarılır.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class FiveExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('V')) context.NumberValue += 5; } } class FiveMinuesExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('V')) context.NumberValue -= 5; } } |
PlusOneExpression.cs & MinuesOneExpression.cs : ‘I’ karakteri için 1 değeri duruma göre ya eklenir yada çıkarılır.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class PlusOneExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('I')) context.NumberValue += 1; } } class MinuesOneExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('I')) context.NumberValue -= 1; } } |
Yukarıda görüldüğü gibi tüm Termianl classlar Interpret işlemi yaparak ilgili Context’in NumberValue değerine ilgili roma rakamının sayısal karşılığına göre, büyük sayının solunda ise çıkarıp azaltır yada sağında ise ekleyerek arttırır.
Aşşağıda görüldüğü gibi context içindeki string roma rakamı Formula olarak tanımlanmakta ve CreateExpressionTree methodu ile gerekti TerminalExpression classlar oluşturularak herbiri için Interpret işlemi ilgili context için çağrılmaktadır.
1 2 3 4 5 6 7 8 |
public static int RunExpression(Context context) { foreach (RoleExpression rex in CreateExpressionTree(context.Formula)) { rex.Interpret(context); } return context.NumberValue; } |
Aşşağıda görüldüğü gibi öncelikle ilgili Roma rakamlarının sayısal karşılığı RomNumber Dictionary içinde tanımlanmıştır. Gelen Formula içindeki herbir karakter diziye atılmış ve işlenmek amacı ile ters çevrilmiştir. Yani roma rakamı için işleme soldan sağ olarak devam edilir. Herbir karakter’e göre tanımlı TerminalExpression’lar bir önceki değerle karşılaştırılarak öncekinden büyük veya eşit ise arttıran değil ise azaltan expression olarak RoleExpression listesine eklenir.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
static List<RoleExpression> CreateExpressionTree(string Formula) { Dictionary<string, int> RomNumber = new Dictionary<string, int>(); RomNumber.Add("M", 1000); RomNumber.Add("D", 500); RomNumber.Add("C", 100); RomNumber.Add("L", 50); RomNumber.Add("X", 10); RomNumber.Add("V", 5); RomNumber.Add("I", 1); List<RoleExpression> tree = new List<RoleExpression>(); char[] chrDizi = Formula.ToCharArray(); Array.Reverse(chrDizi); for (int i = 0; i < chrDizi.Length; i++) { switch (chrDizi[i]) { case 'M': { tree.Add(new ThousendExpression()); break; } case 'D': { if (i > 0 && RomNumber[chrDizi[i].ToString()] >= RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new FiveHunderdExpression()); else if (i > 0 && RomNumber[chrDizi[i].ToString()] < RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new FiveHunderdMinuesExpression()); else if (i == 0) tree.Add(new FiveHunderdExpression()); break; } case 'C': { if (i > 0 && RomNumber[chrDizi[i].ToString()] >= RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new HunderdExpression()); else if (i > 0 && RomNumber[chrDizi[i].ToString()] < RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new HunderdMinuesExpression()); else if (i == 0) tree.Add(new HunderdExpression()); break; } case 'L': { if (i > 0 && RomNumber[chrDizi[i].ToString()] >= RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new FiftyExpression()); else if (i > 0 && RomNumber[chrDizi[i].ToString()] < RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new FiftyMinuesExpression()); else if (i == 0) tree.Add(new FiftyExpression()); break; } case 'X': { if (i > 0 && RomNumber[chrDizi[i].ToString()] >= RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new TenExpression()); else if (i > 0 && RomNumber[chrDizi[i].ToString()] < RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new TenMinuesExpression()); else if (i == 0) tree.Add(new TenExpression()); break; } case 'V': { if (i > 0 && RomNumber[chrDizi[i].ToString()] >= RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new FiveExpression()); else if (i > 0 && RomNumber[chrDizi[i].ToString()] < RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new FiveMinuesExpression()); else if (i == 0) tree.Add(new FiveExpression()); break; } case 'I': { if (i > 0) { bool boolMines = false; for (int s = i - 1; s >= 0; s--) { if (chrDizi[s].ToString() != "I") boolMines = true; break; } if (boolMines) { tree.Add(new MinuesOneExpression()); } else tree.Add(new PlusOneExpression()); } else if (i == 0) { tree.Add(new PlusOneExpression()); } break; } } } return tree; } |
Yukarıda görüldüğü gibi önceden belirlenen TerminalExpressionlar’a göre ilgili formula tek tek interpret işlemine sokulur ve girilen roma rakamına karşılık gelen sayı bulunur. Şimdi de bu servisi çağıran WebApplication’ı yazalım.
Aşşağıda görüldüğü gibi Index.cshtml’de tanımlanmış ajax.post ilgili webapi servisine istenen roma rakamı değerini post edip result’ı yazar.
InterpreterController.cs: Aşşağıda görüldüğü gibi ilgili webapi servisi gelen roma rakamını static operation class’ının RunExpression methodu ile çözümleyip ilgili sayısal değeri döndürmektedir.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using Interpreter.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Cors; namespace Interpreter.Controllers { [EnableCors(origins: "*", headers: "*", methods: "*")] public class InterpreterController : ApiController { // POST api/values public int Post([FromBody] string content) { return Operation.RunExpression(new Context() { Formula=content.ToUpper()}); } } } |
HomeController.cs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace RomanNumeralsConverter.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } } } |
Index.cshtml:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
@{ ViewBag.Title = "Home Page"; } <script> function send() { $.ajax({ type: 'POST', url: 'http://romanconverter.azurewebsites.net/api/Interpreter', data: JSON.stringify($('#txtNumber').val()), contentType: "application/json; charset=utf-8", traditional: true, success: function (data) { if(data!=0) { $('#txtResult').val(data); } else{ alert($('#txtNumber').val() + " is not a vail input!") $('#txtResult').val(); } } }); } </script> <body background="~/Content/egypt2.jpg"> <div class="jumbotron" style="font-family:Greek"> <table> <tr> <td> <b>Roman Number :</b> </td> <td> <input type="text" id="txtNumber" /> </td> <td> <button onclick="send();">Send Content</button> </td> </tr> <tr><td></td></tr> <tr> <td> <b>Result Number :</b> </td> <td> <input type="text" id="txtResult" readonly="readonly"/> </td> </tr> </table> </div> <div class="row" > <h1 style="font-family:Greek">Let's Convert Roman Number</h1> <p> </p> </div> </body> |
Yukarıda görüldüğü gibi düzenli bir metin olan roma rakamları önceden herbir karakter için tanımlı TerminalExpression ile interpret adındaki işeleme tabi tutularak context class’ı altında sonuç döndürülmektedir. Amaç karmaşık yapıları kendine özel operationlar ile farklı işlemlere bölerek yapıyı mümkün olduğunca basite indirgemek ve yeni bir algoritma sisteme dahil olduğunda bunun çözümü amacı ile yeni bir operation ekliyerek, var olan sistemde mümkün olduğunca az işlem ile değişikliğe gidebilmektir.
Operation.cs (Tümü):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 |
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Interpreter.Models { public static class Operation { static List<RoleExpression> CreateExpressionTree(string Formula) { Dictionary<string, int> RomNumber = new Dictionary<string, int>(); RomNumber.Add("M", 1000); RomNumber.Add("D", 500); RomNumber.Add("C", 100); RomNumber.Add("L", 50); RomNumber.Add("X", 10); RomNumber.Add("V", 5); RomNumber.Add("I", 1); List<RoleExpression> tree = new List<RoleExpression>(); char[] chrDizi = Formula.ToCharArray(); Array.Reverse(chrDizi); for (int i = 0; i < chrDizi.Length; i++) { switch (chrDizi[i]) { case 'M': { tree.Add(new ThousendExpression()); break; } case 'D': { if (i > 0 && RomNumber[chrDizi[i].ToString()] >= RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new FiveHunderdExpression()); else if (i > 0 && RomNumber[chrDizi[i].ToString()] < RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new FiveHunderdMinuesExpression()); else if (i == 0) tree.Add(new FiveHunderdExpression()); break; } case 'C': { if (i > 0 && RomNumber[chrDizi[i].ToString()] >= RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new HunderdExpression()); else if (i > 0 && RomNumber[chrDizi[i].ToString()] < RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new HunderdMinuesExpression()); else if (i == 0) tree.Add(new HunderdExpression()); break; } case 'L': { if (i > 0 && RomNumber[chrDizi[i].ToString()] >= RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new FiftyExpression()); else if (i > 0 && RomNumber[chrDizi[i].ToString()] < RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new FiftyMinuesExpression()); else if (i == 0) tree.Add(new FiftyExpression()); break; } case 'X': { if (i > 0 && RomNumber[chrDizi[i].ToString()] >= RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new TenExpression()); else if (i > 0 && RomNumber[chrDizi[i].ToString()] < RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new TenMinuesExpression()); else if (i == 0) tree.Add(new TenExpression()); break; } case 'V': { if (i > 0 && RomNumber[chrDizi[i].ToString()] >= RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new FiveExpression()); else if (i > 0 && RomNumber[chrDizi[i].ToString()] < RomNumber[chrDizi[i - 1].ToString()]) tree.Add(new FiveMinuesExpression()); else if (i == 0) tree.Add(new FiveExpression()); break; } case 'I': { if (i > 0) { bool boolMines = false; for (int s = i - 1; s >= 0; s--) { if (chrDizi[s].ToString() != "I") boolMines = true; break; } if (boolMines) { tree.Add(new MinuesOneExpression()); } else tree.Add(new PlusOneExpression()); } else if (i == 0) { tree.Add(new PlusOneExpression()); } break; } } } return tree; } public static int RunExpression(Context context) { foreach (RoleExpression rex in CreateExpressionTree(context.Formula)) { rex.Interpret(context); } return context.NumberValue; } } public class Context { public string Formula { get; set; } public int NumberValue { get; set; } } abstract class RoleExpression { public abstract void Interpret(Context context); } class ThousendExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('M')) context.NumberValue += 1000; } } class FiveHunderdExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('D')) context.NumberValue += 500; } } class FiveHunderdMinuesExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('D')) context.NumberValue -= 500; } } class HunderdExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('C')) context.NumberValue += 100; } } class HunderdMinuesExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('C')) context.NumberValue -= 100; } } class FiftyExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('L')) context.NumberValue += 50; } } class FiftyMinuesExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('L')) context.NumberValue -= 50; } } class TenExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('X')) context.NumberValue += 10; } } class TenMinuesExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('X')) context.NumberValue -= 10; } } class FiveExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('V')) context.NumberValue += 5; } } class FiveMinuesExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('V')) context.NumberValue -= 5; } } class PlusOneExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('I')) context.NumberValue += 1; } } class MinuesOneExpression : RoleExpression { public override void Interpret(Context context) { if (context.Formula.Contains('I')) context.NumberValue -= 1; } } } |
Yeni bir makalede görüşmek üzere hoşçakalın.
Herkese iyi bayramlar…
Test Url : http://romannumerals.azurewebsites.net
Test WebApi Url : https://romanservice.azurewebsites.net/api/Interpreter
Source Code : http://www.borakasmer.com/projects/Interpreter.rar
GitHub : https://github.com/borakasmer/Interpreter
Source:
IIV gibi rakamlarla çalışmıyor galiba kodunuz.Eşitlik durumunda daima Increment ettiğiniz için.
Selamlar Anıl,
Makaledeki Test Url’i açtım. Ben denedim 5 veriyor. Sanırım bunun gibi “IIV” geçersiz roma rakkamlarını koda dahil etmemişim.
İlerde kodları bu duruma göre tekrardan güncellemeye çalışırım.
Düzeltme için teşekkürler.
İyi çalışmalar.