意图:工具
用一个容器来管理一系列相同的逻辑实现,这些相同的逻辑实现都源自同一个抽象;经过容器根据具体的逻辑来建立具体的逻辑处理实现对象,从而能够为未来的逻辑实现扩展制定出一个标准,以达到未来的实现逻辑能够平滑的插入到容器中来达到将来的同类实现逻辑的扩展。spa
适用性:设计
当发现一些逻辑用来处理类似的业务时,而且只是由于某一个固定的关键节点不一样,其余处理很类似时code
而且将来还会有相似的 处理逻辑添加进来时对象
是否是感受有点云里雾里的,那先看下代码吗。因为手头目前没有任何的画图工具,以后会补上UML图。blog
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就是了。从总体上这个模式遵循了面向对象的开闭原则,对扩展是打开的,对已有的实现修改对关闭的。get
很方便支持扩展,固然你的构建实现类的代码须要通过本身面向对象的设计来规避对已有代码修改的关闭的,你能够采用抽象工厂之类或其余的设计来封装这块代码。string
先写到这里吧,该下班了,明天再作详细的解释和审验。io