版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、设计模式总览,码农的生活,枯燥 乏味 单调 缺乏激情,我们该怎么办?,理想:代码就像模块化的黑箱子,CHANGE!,The one constant in software development:,防止紧耦合,紧耦合带来的麻烦,设计模式怎么学,什么是设计模式? 设计模式的作用是什么? 设计模式都有哪些? 每个模式都是怎么回事? 每个模式都适用什么场合?,History of Software Patterns,What Wikipedia says,A design pattern is a general repeatable solution to a commonly occurrin
2、g problem in software design. A design pattern is not a finished design that can be transformed directly into code. Algorithms are not thought of as design patterns.,什么是设计模式?,设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。 软件设计的某些特定场合的某些问题的解决思路. 是前人经过大量的实践,总结出来的无论从效率上,扩展性,复用性,可靠性等方面都显现出优势的解决思
3、路。,什么是设计模式?,Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice“ (Christopher Alexander),“Pattern
4、 is a named and well-known problem/solution pair that can be applied in new contexts, with advice on how to apply it in novel situations and discussion of its trade-offs, implementations, variations, and so forth.” (Craig Larman),设计模式的作用是什么?,设计的重用; 为设计提供共同的词汇,每个模式名就是一个设计词汇,其概念使得程序员的交流变得方便; 在开发文档中采用模
5、式词汇可以让其他人更容易理解你的想法。,模式的基本元模型,Basic Pattern Metamodel,Problem,Solution,Consequence,Pattern,name,*,THE SACRED ELEMENTS OF THE FAITH,GoF是Gang of Four的简称,翻成中文就是“四人帮”; 这四个人分别是Gamma, Johnson, Helm, Vlissides; 他们在1995出版了Design Patterns: Elements of Reusable Object-Oriented Software(设计模式:可复用面向对象软件的基础)这本书而声名
6、大噪; 研读Design Patterns必读的经典书; 书中所提到的23个Design Patterns也是最常见也是最根本的。,GoF - Design Patterns,Creation Patterns Abstract Factory Builder Factory Method Prototype Method Singleton,Structural Patterns Adapter Bridge Composite Decorator Facade Flyweight Proxy,Behavioral Patterns Chain of Responsibility Comma
7、nd Interpreter Iterator Mediator Memento Observer State Strategy Template Method Visitor,The Gang of Four in their heyday. Ralph, Erich, Richard, and John at OOPSLA 1994.,GoF Patterns Classification,By Purpose,By Scope,第一是目的准则,即模式是用来完成什么工作的。模式依据其目的可分为创建型( Creational)、结构型( Structural)、或行为型( Behaviora
8、l )三种。创建型模式与对象的创建有关;结构型模式处理类或对象的组合;行为型模式对类或对象怎样交互和怎样分配职责进行描述。,第二是范围准则,指定模式主要是用于类还是用于对象。Class模式:在具体化时需要使用继承(extends)。Object模式:在实现时除了接口继承(implements)外不需要其他关键字。这个情况比上一种的模式多得多,也说明了在面向对象编程中提倡面向接口编程而不是基于继承。 。,Lets understand the purpose,+,Lets understand the purpose,创建型设计模式,创建型模式是用来创建对象的模式,抽象了实例化的过程,帮助一个系
9、统独立于其关联对象的创建、组合和表示方式 创建型模式具有两个功能 将系统所使用的具体类的信息封装起来 隐藏类的实例是如何被创建和组织的。外界对于这些对象只知道它们共同的接口,而不清楚其具体的实,Room room = new ModernRoom(); / 现代风格房屋,Room room = new ClassicalRoom(); / 古典风格房屋,RoomFactory factory = new ModernRoomFactory(); Room modernRoom = factory.create();,RoomFactory factory = new ClassicalRoom
10、Factory(); Room classicalRoom = factory.create();,单例模式(Singleton Pattern) 工厂方法模式(Factory Pattern) 抽象工厂模式(Abstract Factory) 建造者模式(Builder Pattern) 原型模式(Prototype Pattern),结构型设计模式,代理模式(Proxy) 为其他对象提供一种代理以控制对该对象的访问 装饰模式(Decorator) 动态地给一个对象添加一些额外的职责 适配器模式(Adapter) 将一个类的接口变换成客户端所期待的另一接口 组合模式(Composite) 将
11、对象组合成树形结构以表示“部分-整体”的层次结构 桥梁模式(Bridge) 将抽象和实现解耦,使得两者可以独立的变化 外观模式(Facade) 要求一个子系统的外部与其内部的通信必须通过一个统一的对象进行 享元模式(Flyweight) 池技术的重要实现方式,使用共享对象可有效地支持大量的细粒度的对象,行为型设计模式 - 1,模板方法模式(Template Method) 定义一个操作中的算法的框架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤 命令模式(Command) 将一个请求封装成一个对象,从而使用不同的请求把客户端参数化,对请求排队或者记录
12、请求日志,可以提供命令的撤销和恢复功能 责任链模式(Chain of Responsibility) 使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止 策略模式(Strategy) 定义一组算法,将每个算法都封装起来,并且使它们之间可以互换 迭代器模式(Iterator) 访问一个容器对象中的各个元素,而又不需要暴露该对象的内部细节,行为型设计模式 - 2,中介者模式(Mediator) 用一个中介对象封装一系列的对象交互,中介者使各对象不需要显示的相互作用,从而使其耦合松散,而且可以独立的改变他们之间
13、的交互 观察者模式(Observer) 定义对象间的一种一对多的依赖关系,使得每当一个对象改变状态,则所有依赖于它的对象都会得到通知并被自动更新责任链 备忘录模式(Memento) 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态 访问者模式(Visitor) 封装一些作用于某种数据结构中的各元素的操作,它可以在不改变数据结构的前提下定义作用于这些元素的新的操作 状态模式(State) 当一个对象内在状态改变时允许其改变行为 解释器模式(Interpreter) 给定一门语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该文法表示来解释语言中的句子,GOF
14、DPs in JDK,Abstract factory (recognizeable by creational methods returning an abstract/interface type) java.util.Calendar#getInstance() java.util.Arrays#asList() java.util.ResourceBundle#getBundle() .URL#openConnection() java.sql.DriverManager#getConnection() java.sql.Connection#createStatement() ja
15、va.sql.Statement#executeQuery() java.text.NumberFormat#getInstance() java.lang.management.ManagementFactory (all getXXX() methods) java.nio.charset.Charset#forName() javax.xml.parsers.DocumentBuilderFactory#newInstance() javax.xml.transform.TransformerFactory#newInstance() javax.xml.xpath.XPathFacto
16、ry#newInstance() .URLStreamHandlerFactory#createURLStreamHandler(String) (Returns singleton object per protocol),Builder (recognizeable by creational methods returning the instance itself) java.lang.StringBuilder#append() (unsynchronized) java.lang.StringBuffer#append() (synchronized) java.nio.ByteB
17、uffer#put() (also on CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer and DoubleBuffer) javax.swing.GroupLayout.Group#addComponent() All implementations of java.lang.Appendable,Factory method (recognizeable by creational methods returning a concrete type) java.lang.Object#toString() (over
18、rideable in all subclasses) java.lang.Class#newInstance() java.lang.Integer#valueOf(String) (also on Boolean, Byte, Character, Short, Long, Float and Double) java.lang.Class#forName() java.lang.reflect.Array#newInstance() java.lang.reflect.Constructor#newInstance(),Prototype (recognizeable by creati
19、onal methods returning a different instance of itself with the same properties) java.lang.Object#clone() (the class has to implement java.lang.Cloneable) Singleton (recognizeable by creational methods returning the same instance (usually of itself) everytime) java.lang.Runtime#getRuntime() java.awt.
20、Desktop#getDesktop(),Structural patterns Adapter (recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own/another abstract/interface type which decorates/overrides the given instance) java.io.InputStreamReader(InputStream) (r
21、eturns a Reader) java.io.OutputStreamWriter(OutputStream) (returns a Writer) javax.xml.bind.annotation.adapters.XmlAdapter#marshal() and #unmarshal() Bridge (recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own abstract/in
22、terface type which delegates/uses the given instance) None comes to mind yet. A fictive example would be new LinkedHashMap(LinkedHashSet, List) which returns an unmodifiable linked map which doesnt clone the items, but uses them. The java.util.Collections#newSetFromMap() and singletonXXX() methods h
23、owever comes close. Composite (recognizeable by behavioral methods taking an instance of same abstract/interface type into a tree structure) java.awt.Container#add(Component) (practically all over Swing thus) ponent.UIComponent#getChildren() (practically all over JSF UI thus),Decorator (recognizeabl
24、e by creational methods taking an instance of same abstract/interface type which adds additional behaviour) All subclasses of java.io.InputStream, OutputStream, Reader and Writer have a constructor taking an instance of same type. java.util.Collections, the checkedXXX(), synchronizedXXX() and unmodi
25、fiableXXX() methods. javax.servlet.http.HttpServletRequestWrapper and HttpServletResponseWrapper Facade (recognizeable by behavioral methods which internally uses instances of different independent abstract/interface types) javax.faces.context.FacesContext, it internally uses among others the abstra
26、ct/interface types LifeCycle, ViewHandler, NavigationHandler and many more without that the enduser has to worry about it (which are however overrideable by injection). javax.faces.context.ExternalContext, which internally uses ServletContext, HttpSession, HttpServletRequest, HttpServletResponse, et
27、c. Flyweight (recognizeable by creational methods returning a cached instance, a bit the multiton idea) java.lang.Integer#valueOf(int) (also on Boolean, Byte, Character, Short, Long, Float and Double) Proxy (recognizeable by creational methods which returns an implementation of given abstract/interf
28、ace type which in turn delegates/uses a different implementation of given abstract/interface type) java.lang.reflect.Proxy java.rmi.*, the whole API actually.,Behavioral patterns Chain of responsibility (recognizeable by behavioral methods which (indirectly) invokes the same method in another implem
29、entation of same abstract/interface type in a queue) java.util.logging.Logger#log() javax.servlet.Filter#doFilter() Command (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been encapsulate
30、d by the command implementation during its creation) All implementations of java.lang.Runnable All implementations of javax.swing.Action Interpreter (recognizeable by behavioral methods returning a structurally different instance/type of the given instance/type; note that parsing/formatting is not p
31、art of the pattern, determining the pattern and how to apply it is) java.util.Pattern java.text.Normalizer All subclasses of java.text.Format All subclasses of javax.el.ELResolver,Iterator (recognizeable by behavioral methods sequentially returning instances of a different type from a queue) All imp
32、lementations of java.util.Iterator (thus among others also java.util.Scanner!). All implementations of java.util.Enumeration Mediator (recognizeable by behavioral methods taking an instance of different abstract/interface type (usually using the command pattern) which delegates/uses the given instan
33、ce) java.util.Timer (all scheduleXXX() methods) java.util.concurrent.Executor#execute() java.util.concurrent.ExecutorService (the invokeXXX() and submit() methods) java.util.concurrent.ScheduledExecutorService (all scheduleXXX() methods) java.lang.reflect.Method#invoke() Memento (recognizeable by be
34、havioral methods which internally changes the state of the whole instance) java.util.Date (the setter methods do that, Date is internally represented by a long value) All implementations of java.io.Serializable All implementations of ponent.StateHolder Observer (or Publish/Subscribe) (recognizeable
35、by behavioral methods which invokes a method on an instance of another abstract/interface type, depending on own state) java.util.Observer/java.util.Observable (rarely used in real world though) All implementations of java.util.EventListener (practically all over Swing thus) javax.servlet.http.HttpS
36、essionBindingListener javax.servlet.http.HttpSessionAttributeListener javax.faces.event.PhaseListener,State (recognizeable by behavioral methods which changes its behaviour depending on the instances state which can be controlled externally) javax.faces.lifecycle.LifeCycle#execute() (controlled by F
37、acesServlet, the behaviour is dependent on current phase (state) of JSF lifecycle) Strategy (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been passed-in as method argument into the strat
38、egy implementation) java.util.Comparator#compare(), executed by among others Collections#sort(). javax.servlet.http.HttpServlet, the service() and all doXXX() methods take HttpServletRequest and HttpServletResponse and the implementor has to process them (and not to get hold of them as instance vari
39、ables!). javax.servlet.Filter#doFilter(),Template method (recognizeable by behavioral methods which already have a default behaviour definied by an abstract type) All non-abstract methods of java.io.InputStream, java.io.OutputStream, java.io.Reader and java.io.Writer. All non-abstract methods of jav
40、a.util.AbstractList, java.util.AbstractSet and java.util.AbstractMap. javax.servlet.http.HttpServlet, all the doXXX() methods by default sends a HTTP 405 Method Not Allowed error to the response. Youre free to implement none or any of them. Visitor (recognizeable by two different abstract/interface
41、types which has methods definied which takes each the other abstract/interface type; the one actually calls the method of the other and the other executes the desired strategy on it) javax.lang.model.element.AnnotationValue and AnnotationValueVisitor javax.lang.model.element.Element and ElementVisitor javax.lang.model.type.TypeMirror and TypeVisitor,小结,设计一个模式的过程就是将问题抽象化,忽略不重要的细节后发现问题的本质,并找到普遍适用的解决方案的过程 GoF的设计模式提供了一套可复用的面向对象技术 设计模式起源于建筑设计学 设计模式的基本要素是:名字、问题、初始环境、举例、末态环境、推理、其他有关模式、已知应用 设计模式
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2026奶茶创业计划书选址评估报告
- 2024年淄博现代职业学院高职单招职业技能考试模拟试卷含完整答案详解【必刷】
- 2024年甘肃建筑职业学院高职单招职业技能考试模拟试卷含完整答案详解【各地真题】
- 2024年枣庄抱犊崮职业学院高职单招职业适应性测试考试题库含答案详解(完整版)
- 2025年浙江省绍兴市单招职业技能考试模拟试卷完整答案详解
- 2027年桥山职业学院高职单招职业适应性测试考试题库及答案详解【名师系列】
- 2026挪威海洋渔业发展前景与产业价值评估研究报告
- 2026中国涡流泵行业区域市场差异与渠道拓展路径报告
- 2026中国阵列式传感器工业质检设备更新需求测算研究报告
- 2026中国温湿度传感器行业标准与市场渗透率研究报告
- 2026年领导干部任前廉政法规知识竞赛试题库及答案
- 山东能源定向委培考试题
- 境外病人收治流程
- 加油站工程工程施工组织设计方案
- HY/T 0330-2022海滩养护与修复工程验收技术方法
- NY 526-2002水稻苗床调理剂
- JJG 1029-2007涡街流量计
- GB/T 34904-2017球墨铸铁件超声检测
- UCP600-ISBP745及案例专题培训课件
- 专题一:运动图像-追及-相遇问题
- GB∕T 4146.1-2020 纺织品 化学纤维 第1部分:属名
评论
0/150
提交评论