此篇post介绍了一种代码模式,此模式可以让多个方法(这些方法可以分布在不同的对象中)共享一个database对象。
假如有两个对象ObjBillAMgr和ObjBillBMgr,ObjBillAMgr的Save方法和ObjBillBMgr的Save方法中的Sql需要在一个事务中执行,也可能单独执行,如何处理?我们可以在.NET FX2.0中使用TransactionScope对象处理,但是需要服务器必须启用DTC。而且在.NET FX 1.1里是没有TransactionScope的。我们原始的做法是:
1 class BillAMgr
2 {
3 void Save(){Database a = new Database(); this.Save(a);}
4 void Save(Database db){db.Execute("insert ")}
5 }
6
7 class BillBMgr
8 {
9 void Save(){Database a = new Database(); this.Save(a);}
10 void Save(Database db){db.Execute("insert ")}
11 }
2 {
3 void Save(){Database a = new Database(); this.Save(a);}
4 void Save(Database db){db.Execute("insert ")}
5 }
6
7 class BillBMgr
8 {
9 void Save(){Database a = new Database(); this.Save(a);}
10 void Save(Database db){db.Execute("insert ")}
11 }
单独执行 Client Code:
1 BillAMgr ObjBillAMgr = new BillAMgr();
2 BillBMgr ObjBillBMgr = new BillBMgr();
3 ObjBillAmgr.Save();
4 ObjBillBmgr.Save();
2 BillBMgr ObjBillBMgr = new BillBMgr();
3 ObjBillAmgr.Save();
4 ObjBillBmgr.Save();
需在事务中执行 Client Code:
1 BillAMgr ObjBillAMgr = new BillAMgr();
2 BillBMgr ObjBillBMgr = new BillBMgr();
3 Database db = new Database();
4 db.BeginTransaction();
5 ObjBillAmgr.Save(db);
6 ObjBillBmgr.Save(db);
7 db.Comit();
2 BillBMgr ObjBillBMgr = new BillBMgr();
3 Database db = new Database();
4 db.BeginTransaction();
5 ObjBillAmgr.Save(db);
6 ObjBillBmgr.Save(db);
7 db.Comit();
以上代码我们为了让Save方法共享Database对象,Save方法必须重载一次,像这样的方法千千万,我们都要重写的话工作量太大。以下为新的模式
1 interface IDBExecutor
2 {
3 Database DB { get; set; }
4 }
5
6 class DBExcecutor : IDBExecutor
7 {
8 private Database _db = null;
9
10 public Database DB
11 {
12 get
13 {
14 if(this._db == null) this._db = new Database();
15 return this._db;
16 }
17 set
18 {
19 this._db = value;
20 }
21 }
22 }
23
24 class BillAMgr:DBExecutor
25 {
26 void Save(){this.DB.Execute("Insert ");}
27 }
28
29 class BillBMgr:DBExecutor
30 {
31 void Save(){this.DB.Execute("Insert ");}
32 }
2 {
3 Database DB { get; set; }
4 }
5
6 class DBExcecutor : IDBExecutor
7 {
8 private Database _db = null;
9
10 public Database DB
11 {
12 get
13 {
14 if(this._db == null) this._db = new Database();
15 return this._db;
16 }
17 set
18 {
19 this._db = value;
20 }
21 }
22 }
23
24 class BillAMgr:DBExecutor
25 {
26 void Save(){this.DB.Execute("Insert ");}
27 }
28
29 class BillBMgr:DBExecutor
30 {
31 void Save(){this.DB.Execute("Insert ");}
32 }
单独执行 Client Code:没有改变
需在事务中执行 Client Code:
1 BillAMgr ObjBillAMgr = new BillAMgr();
2 BillBMgr ObjBillBMgr = new BillBMgr();
3 Database db = new Database();
4 db.BeginTransaction();
5 ObjBillAMgr.DB = db;
6 ObjBillBMgr.DB = db;
7 ObjBillAMgr.Save();
8 ObjBillBMgr.Save();
9 db.Comit();
2 BillBMgr ObjBillBMgr = new BillBMgr();
3 Database db = new Database();
4 db.BeginTransaction();
5 ObjBillAMgr.DB = db;
6 ObjBillBMgr.DB = db;
7 ObjBillAMgr.Save();
8 ObjBillBMgr.Save();
9 db.Comit();
这样,业务处理类中就没有必要为共享database而重载方法了。如果你的业务处理类已经继承了其他父类,可以实现IDBExecutor 来实现。
一点儿想法,请指教。