目前,Im试图实施Transaction 字典模式(实际上,Martin Fowler 。 通过在简单的测试项目中使用Command Format,一切只是工作罚款,问题在于我不知道如何在从ICommand界面继承的具体类别中执行特定方法时取得结果。
Let s show you some code to clarify what functionality I have. I ve a simple CalculateSalaryCommand class which inherited from ICommand interface
public class CalculateSalaryCommand : ICommand
{
private readonly CalculateSalaryTS _salaryTs;
private readonly int _hour;
private readonly int _salaryPerHour;
public CalculateSalaryCommand(CalculateSalaryTS salaryTs, int hour, int salaryPerHour)
{
_salaryTs = salaryTs;
_hour = hour;
_salaryPerHour = salaryPerHour;
}
public void Execute()
{
_salaryTs.CalculateSalary(_hour, _salaryPerHour);
}
}
and a simple Transaction Script class named CalculateSalaryTS
public class CalculateSalaryTS {
public void CalculateSalary(int _hour, int _salaryPerHour) {
Result = _hour * _salaryPerHour;
}
}
as you can see I pass the instance of to concrete command class, then inside the Execute method I execute a operations from that instance. Well, everything just look good. but there is a problem I can t return the result of executed method which is should be a integer.
To handle this problem, I decided to add some code to Transaction Script layer which each transaction should inherit from a generic ITransactionResult
interface, which is look like following:
public interface ITransactionResult<TResult>
{
TResult Result { get; set; }
}
然后,计算仪表相仿:
public class CalculateSalaryTS : ITransactionResult<Int32> {
public void CalculateSalary(int _hour, int _salaryPerHour) {
Result = _hour * _salaryPerHour;
}
public int Result { get; set; }
}
<<>Usage>:
var script = new CalculateSalaryTS();
var command = new CalculateSalaryCommand(script, 10, 20);
command.Execute();
Console.WriteLine("Salary is {0}", script.Result);
我知道这种方式有其局限性,但我别无选择,直到你给我另一种处理这种情况的想法。
提前感谢。