设计模式入门(1)

每一个模式描述了一个在我们周围不断重复发生的问题,以及该问题的解决方案的核心。
——Christopher Alexander

设计模式描述了软件设计过程中某一类常见问题的一般性的解决方案。

面向对象设计模式描述了面向对象设计过程中、特定场景下、类与相互通信的对象之间常见的组织关系

 

• 面向对象设计模式解决的是“类与相互通信的对象之间的组织关系,包括它们的角色、职责、协作方式几个方面。
• 面向对象设计模式是“好的面向对象设计”,所谓“好的面向对象设计”是那些可以满足“应对变化,提高复用”的设计。
• 面向对象设计模式描述的是软件设计,因此它是独立于编程语言的,但是面向对象设计模式的最终实现仍然要使用面向对象编程语言来表达。

• 面向对象设计模式不像算法技巧,可以照搬照用,它是建立在对“面向对象”纯熟、深入的理解的基础上的经验性认识。掌握面向对象设计模式的前提是首先掌握“面向对象”!

 

各种面向对象编程语言相互有别,但都能看到它们对面向对象三大机制的支持,即: “封装、继承、多态”
– 封装,隐藏内部实现
– 继承,复用现有代码
– 多态,改写对象行为

  

 面向对象设计原则

• 针对接口编程,而不是针对实现编程
– 客户无需知道所使用对象的特定类型,只需要知道对象拥有客户所期望的接口。
• 优先使用对象组合,而不是类继承
– 类继承通常为“白箱复用”,对象组合通常为“黑箱复用”。继承在某种程度上破坏了封装性,子类父类耦合度高;而对象组合则只要求被组合的对象具有良好定义的接口,耦合度低。
• 封装变化点
– 使用封装来创建对象之间的分界层,让设计者可以在分界层的一侧进行修改,而不会对另一侧产生不良的影响,从而实现层次间的松耦合。
• 使用重构得到模式

— 设计模式的应用不宜先入为主,一上来就使用设计模式是对设计模式的最大误用。没有一步到位的设计模式。敏捷软件开发实践提倡的“Refactoring to Patterns”是目前普遍公认的最好的使用设计模式的方法。

 

几条更具体的设计原则
• 单一职责原则(SRP):
– 一个类应该仅有一个引起它变化的原因。
• 开放封闭原则(OCP):
– 类模块应该是可扩展的,但是不可修改(对扩展开放,对更改封闭)
• Liskov 替换原则(LSP):
– 子类必须能够替换它们的基类
• 依赖倒置原则(DIP):
– 高层模块不应该依赖于低层模块,二者都应该依赖于抽象。
– 抽象不应该依赖于实现细节,实现细节应该依赖于抽象。
• 接口隔离原则(ISP):
– 不应该强迫客户程序依赖于它们不用的方法。

 

深刻理解面向对象是学好设计模式的基础,掌握一定的面向对象设计原则才能把握面向对象设计模式的精髓,从而实现灵活运用设计模式。

 

创建型模式      
Abstract Factory 抽象工厂 Creates an instance of several families of classes 5
Factory Method 工厂方法 Creates an instance of several derived classes 5
Singleton 单例模式 A class of which only a single instance can exist 4
Prototype 原型方法 A fully initialized instance to be copied or cloned 3
Builder 创建者模式 Separates object construction from its representation 2
       
结构型模式      
Facade 外观模式 A single class that represents an entire subsystem 5
Proxy 代理模式 An object representing another object 4
Composite 组合模式 A tree structure of simple and composite objects 4
Adapter 适配者模式 Match interfaces of different classes 4
Decorator 装饰者模式 Add responsibilities to objects dynamically 3
Bridge 桥接模式 Separates an object’s interface from its implementation 3
Flyweight 享元模式 A fine-grained instance used for efficient sharing 1
       
行为型模式      
Iterator 遍历器 Sequentially access the elements of a collection 5
Observer 观察者模式 A way of notifying change to a number of classes 5
Command 命令模式 Encapsulate a command request as an object 4
Strategy 策略模式 Encapsulates an algorithm inside a class 4
State 状态模式 Alter an object's behavior when its state changes 3
Template Method 模板方法 Defer the exact steps of an algorithm to a subclass 3
Chain of Resp. 职责链模式 A way of passing a request between a chain of objects 2
Mediator 中介者模式 Defines simplified communication between classes 2
Interpreter 解释器模式 A way to include language elements in a program 1
Memento 备忘录模式 Capture and restore an object's internal state 1
Visitor 访问者模式 Defines a new operation to a class without change 1

posted on 2010-09-27 17:21  ice6  阅读(396)  评论(0编辑  收藏  举报

导航