Witam,
Ostatnio zacząłem czytać o wzorcach projektowych i nie jestem pewien czy dobrze zrozumiałem idee Interpretera.
Napisałem więc prosty program do przeliczania walut(GBP->USD,USD->EUR itp). Jak ktoś kto dobrze rozumie temat wzorców może zerknąć na mój kod i dać jakiś komentarz to będe wdzięczny.
namespace BlogInterpreter
{
internal abstract class Context
{
protected Context(double input)
{
Input = input;
}
public double Input { get; set; }
public double Output { get; set; }
public abstract double CurrencyRateGbp { get; set; }
public abstract double CurrencyRateUsd { get; set; }
public abstract double CurrencyRateEur { get; set; }
}
class GbpContext : Context
{
public GbpContext(double input) : base(input)
{
CurrencyRateEur = 1.14449;
CurrencyRateGbp = 1;
CurrencyRateUsd = 1.33494;
}
public sealed override double CurrencyRateGbp { get; set; }
public sealed override double CurrencyRateUsd { get; set; }
public sealed override double CurrencyRateEur { get; set; }
}
class UsdContext : Context
{
public UsdContext(double input) : base(input)
{
CurrencyRateEur = 0.85734;
CurrencyRateGbp = 0.74910;
CurrencyRateUsd = 1;
}
public sealed override double CurrencyRateGbp { get; set; }
public sealed override double CurrencyRateUsd { get; set; }
public sealed override double CurrencyRateEur { get; set; }
}
class EurContext : Context
{
public EurContext(double input) : base(input)
{
CurrencyRateEur = 1;
CurrencyRateGbp = 0.87375;
CurrencyRateUsd = 1.16640;
}
public sealed override double CurrencyRateGbp { get; set; }
public sealed override double CurrencyRateUsd { get; set; }
public sealed override double CurrencyRateEur { get; set; }
}
internal interface IExpression
{
double Interpreter(Context c);
}
internal class ToDollars:IExpression
{
public double Interpreter(Context c)
{
c.Output = c.Input * c.CurrencyRateUsd;
return c.Output;
}
}
internal class ToPounds : IExpression
{
public double Interpreter(Context c)
{
c.Output = c.Input * c.CurrencyRateGbp;
return c.Output;
}
}
internal class ToEuro : IExpression
{
public double Interpreter(Context c)
{
c.Output = c.Input * c.CurrencyRateEur;
return c.Output;
}
}
}
private static void Main()
{
var context = new GbpContext(22.4);
var expressions = new List<IExpression> { new ToDollars(), new ToEuro(), new ToPounds() };
foreach (var expression in expressions)
{
Console.WriteLine(expression.Interpreter(context));
}
Console.ReadLine();
}