DDD:策略模式如何结合动态表达式

企业应用中我们经常会遇到各种业务规则,针对这种规则,我们多数情况会采用策略模式,每种策略对应一个具体类和一个具体的配置界面。但是企业业务的规则经常变化,现有的策略随着时间的推移而不能满足要求,针对这种情况我们可以用动态表达式来解决。

动态表达式:在静态语言中动态的执行代码,目前可选的技术有:动态编译、Iron、Roslyn、内嵌小语言。

今天来测试一下内嵌Javascript:

代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 using Noesis.Javascript;
 8 
 9 namespace JavascriptStudy
10 {
11     class Program
12     {
13         static void Main()
14         {
15             var 用户 = new 用户
16             {
17                 年龄 = 20,
18                 工龄 = 5
19             };
20 
21             Console.WriteLine(new 自定义计算公式().计算基本工资(用户));
22         }
23     }
24 
25     internal interface I基本工资计算
26     {
27         Decimal 计算基本工资(用户 用户);
28     }
29 
30     internal class 自定义计算公式 : I基本工资计算
31     {
32         public decimal 计算基本工资(用户 用户)
33         {
34             var context = new JavascriptContext();
35 
36             context.SetParameter("用户", 用户);
37 
38             const string expression = @"用户.工龄 * 200."; //真实项目从数据库获取
39 
40             var result = context.Run(expression);
41 
42             if (result is int)
43             {
44                 return (int)result;
45             }
46 
47             return (decimal)(float)result;
48         }
49     }
50 
51     internal class 用户
52     {
53         public int 年龄 { get; set; }
54 
55         public int 工龄 { get; set; }
56     }
57 }

posted on 2013-04-01 17:49  幸福框架  阅读(1025)  评论(0编辑  收藏  举报

导航

我要啦免费统计