Net设计模式实例之适配器模式(Adapter Pattern).docx
文本预览下载声明
Net设计模式实例之桥接模式( Bridge Pattern)一、桥接模式简介(Brief Introduction)桥接模式(Bridge Pattern),将抽象部分与它的实现部分分离,使的抽象和实现都可以独立地变化。Decouple an abstraction from its implementation so that the two can vary independently.。什么是聚合/组合:聚合(Aggregation),当对象A被加入到对象B中,成为对象B的组成部分时,对象B和对象A之间为聚合关系。聚合是关联关系的一种,是较强的关联关系,强调的是整体与部分之间的关系。场景:商品和他的规格、样式就是聚合关系。类与类的聚合关系图??组合(Composite),对象A包含对象B,对象B离开对象A没有实际意义。是一种更强的关联关系。人包含手,手离开人的躯体就失去了它应有的作用。场景: Window窗体由滑动条slider、头部Header 和工作区Panel组合而成。类与类的组合关系图聚合与合成原则:尽量使用聚合或者组合,尽量不使用类继承。对象的继承关系是在编译时就定义好的,所以无法在运行时改变从父类继承的实现。子类的实现与它的父类有着非常紧密的依赖关系,以至于父类实现中的任何变化必然会导致子类发生变化。当需要复用子类时,如果集成下来的实现不符合解决新的问题,则父类必然重写或被其他更合适的类替换。这种依赖关系限制了灵活性并最终限制了复用性。二、解决的问题(What To Solve)当系统有多维角度分类时,而每一种分类又有可能变化,这时考虑使用桥接模式比较合适。三、桥接模式分析(Analysis)1、桥接模式结构?Abstraction类:业务抽象类,定义一个抽象接口,维护对Impementor的引用.RefinedAbstraction类:具体实现类,被提炼的抽象Implementor类:定义一个抽象实现类,此抽象类与Abstraction类不一定完全相同。Implementor类提供了一些原始的操作,而Abstraction类是对这些原始操作一个更高层次的封装.ConcreteImplementorA,ConcreteImplementorA类:具体实现2、代码1、业务抽象类Abstraction及其提炼出的具体实现类RefinedAbstractionpublicabstractclassAbstraction{protectedImplementor _implementor;?publicImplementor Implementor {set { _implementor = value; }get { return _implementor; } }?publicvirtualvoid Operation() { _implementor.OperationImp(); }}?publicclassRefinedAbstraction:Abstraction{publicoverridevoid Operation() { _implementor.OperationImp(); }}?2、抽象实现类Implementor 及其具体实现类ConcreteImplementorA和ConcreteImplementorBpublicabstractclassImplementor{publicabstractvoid OperationImp();}?publicclassConcreteImplementorA:Implementor{publicoverridevoid OperationImp() {Console.WriteLine({0} Operation Method,this.GetType().Name); }}?publicclassConcreteImplementorB:Implementor{publicoverridevoid OperationImp() {Console.WriteLine({0} Operation Method, this.GetType().Name); }}?2、客户端代码staticvoidMain(string[] args){Abstraction a1 = newRefinedAbstraction();?// Set implementation and call a1.Implementor = newConcreteImplementorA(); a1.Operation();?// Change implemention and
显示全部