意图:
用一个容器来管理一系列相同的逻辑实现,这些相同的逻辑实现都源自同一个抽象;通过容器根据具体的逻辑来创建具体的逻辑处理实现对象,从而可以为将来的逻辑实现扩展制定出一个标准,以达到将来的实现逻辑可以平滑的插入到容器中来达到未来的同类实现逻辑的扩展。
适用性:
当发现一些逻辑用来处理相似的业务时,并且只是因为某一个固定的关键节点不同,其他处理很相似时
并且未来还会有类似的 处理逻辑添加进来时
是不是感觉有点云里雾里的,那先看下代码吗。由于手头目前没有任何的画图工具,之后会补上UML图。
1 /*扣款设备容器接口*/ 2 public interface ICostContainer 3 { 4 //扣某种货币类型的金额 5 bool cost(Currency currency); 6 } 7 8 public class Currency 9 { 10 public DeviceType{get;set;} 11 public int Balance{get;set;} 12 } 13 14 public class CostContainer 15 { 16 private Dictionary<string, ICostDevice> costDeviceDict = new Dictionary<string, ICostDevice>(); 17 18 public CostContainer() 19 { 20 //通过配置文件,或反射,或其他方式找到所有ICostDevice, 21 //把每个扣款设备add到costDeviceDict 22 costDeviceDict.add(ICostDevice.DeviceType,ICostDevice); 23 ... 24 } 25 26 public bool cost(Currency currency) 27 { 28 CostDeviceContainer costDeviceContainer = //通过一些面向对象的构建方式得到容器对象 29 ICostDevice costDevice = CostContainer.get(currency.DeviceType); 30 if(costDeviceDict == null) return false; 31 return costDevice.cost(currency); 32 } 33 } 34 35 /*扣款设备*/ 36 public interface ICostDevice 37 { 38 String DeviceType{get;} 39 bool Cost(Currency currency); 40 } 41 42 public classs RMBCostDevice:ICostDevice 43 { 44 public String DeviceType 45 { 46 get{return "RMBCoster"} 47 } 48 49 public bool Cost(Currency currency) 50 { 51 // 人民币的扣款设备处理逻辑 52 } 53 } 54 55 public class DollorCostDevice:ICostDevice 56 { 57 public String DeviceType 58 { 59 get{return "DollorCoster"} 60 } 61 62 public bool Cost(Currency currency) 63 { 64 // 美元的扣款设备处理逻辑 65 } 66 }
首先这个模式里有些是固定的,如货币对象。
假如将来会接入英镑的扣款设备,那个这个扣款设备的的逻辑处理类应该实现ICostDevice就是了。从整体上这个模式遵循了面向对象的开闭原则,对扩展是打开的,对已有的实现修改对关闭的。
很方便支持扩展,当然你的构建实现类的代码需要经过自己面向对象的设计来规避对已有代码修改的关闭的,你可以采用抽象工厂之类或其他的设计来封装这块代码。
先写到这里吧,该下班了,明天再做详细的解释和审验。