T3设计模式概要.ppt

上传人:qwe****56 文档编号:80590290 上传时间:2023-03-23 格式:PPT 页数:44 大小:1.65MB
返回 下载 相关 举报
T3设计模式概要.ppt_第1页
第1页 / 共44页
T3设计模式概要.ppt_第2页
第2页 / 共44页
点击查看更多>>
资源描述

《T3设计模式概要.ppt》由会员分享,可在线阅读,更多相关《T3设计模式概要.ppt(44页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、设计模式总览码农的生活枯燥乏味单调缺乏激情我们该怎么办?理想:代码就像模块化的黑箱子CHANGE!The one constant in software development:防止紧耦合紧耦合带来的麻烦设计模式怎么学 什么是设计模式?什么是设计模式?设计设计模式的作用是什么?模式的作用是什么?设计设计模式都有哪些?模式都有哪些?每个每个模式都是怎么回事?模式都是怎么回事?每个每个模式都适用什么场合模式都适用什么场合?History of Software Patterns1987-Cunningham and Beck used Alexanders ideas to develop a

2、small pattern language for Smalltalk1990-The Gang of Four(Gamma,Helm,Johnson and Vlissides)begin work compiling a catalog of design patterns1991-Bruce Anderson gives first Patterns Workshop at OOPSLA1993-Kent Beck and Grady Booch sponsor the first meeting-what is now known as the Hillside Group1995-

3、The Gang of Four(GoF)publish the Design Patterns bookWhat Wikipedia says,A design pattern is a general repeatable solution to a commonly occurring 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 p

4、atterns.什么是设计模式?设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。软件设计的某些特定场合的某些问题的解决思路.是前人经过大量的实践,总结出来的无论从效率上,扩展性,复用性,可靠性等方面都显现出优势的解决思路。什么是设计模式?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 suc

5、h a way that you can use this solution a million times over,without ever doing it the same way twice“(Christopher Alexander)“Pattern 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

6、,implementations,variations,and so forth.”(Craig Larman)设计模式的作用是什么?设计的重用;为设计提供共同的词汇,每个模式名就是一个设计词汇,其概念使得程序员的交流变得方便;在开发文档中采用模式词汇可以让其他人更容易理解你的想法。模式的基本元模型Basic Pattern MetamodelProblemSolutionConsequencePatternname*THE SACRED ELEMENTS OF THE FAITHFMFactory Method107PTPrototype117AFAbstract Factory87BUBu

7、ilder97SSingleton127The role origins(Creational)CPComposite163PXProxy207AAdapter139DDecorator175FAFacade185BRBridge151The role structureFLFlyweight195CRChain of Responsibility223TMTemplateMethod325SRStrategy315CDCommand233MMMemento283MDMediator273STState305OObserver293ITIterator257INInterpreter243VV

8、isitor331The role behaviorsGoF是Gang of Four的简称,翻成中文就是“四人帮”;这四个人分别是Gamma,Johnson,Helm,Vlissides;他们在1995出版了Design Patterns:Elements of Reusable Object-Oriented Software(设计模式:可复用面向对象软件的基础)这本书而声名大噪;研读Design Patterns必读的经典书;书中所提到的23个Design Patterns也是最常见也是最根本的。GoF-Design PatternsCreation PatternsAbstract F

9、actoryBuilderFactory MethodPrototype MethodSingletonStructural PatternsAdapterBridgeCompositeDecoratorFacadeFlyweightProxyBehavioral PatternsChain of ResponsibilityCommandInterpreterIteratorMediatorMementoObserverStateStrategyTemplate MethodVisitorThe Gang of Four in their heyday.Ralph,Erich,Richard

10、,and John at OOPSLA 1994.GoF Patterns ClassificationBy PurposeBy Scope第一是目的准则,即模式是用来完成什么工作的。模式依据其目的可分为创建型(Creational)、结构型(Structural)、或行为型(Behavioral)三种。创建型模式与对象的创建有关;结构型模式处理类或对象的组合;行为型模式对类或对象怎样交互和怎样分配职责进行描述。第二是范围准则,指定模式主要是用于类还是用于对象。Class模式:在具体化时需要使用继承(extends)。Object模式:在实现时除了接口继承(implements)外不需要其他关

11、键字。这个情况比上一种的模式多得多,也说明了在面向对象编程中提倡面向接口编程而不是基于继承。Lets understand the purpose+Creational PatternsStructural PatternsFinal ProductBehavioral PatternsLets understand the purposeconcerns the process of object creationCreationallarger structures of classes or objectsStructuralinteraction and distribution of

12、 responsibilityBehavioral创建型设计模式创建型模式是用来创建对象的模式,抽象了实例化的过程,帮助一个系统独立于其关联对象的创建、组合和表示方式 创建型模式具有两个功能 将系统所使用的具体类的信息封装起来 隐藏类的实例是如何被创建和组织的。外界对于这些对象只知道它们共同的接口,而不清楚其具体的实Room room=new ModernRoom();/现代风格房屋Room room=new ClassicalRoom();/古典风格房屋RoomFactory factory=new ModernRoomFactory();Room modernRoom=factory.cr

13、eate();RoomFactory factory=new ClassicalRoomFactory();Room classicalRoom=factory.create();单例模式(Singleton Pattern)工厂方法模式(Factory Pattern)抽象工厂模式(Abstract Factory)建造者模式(Builder Pattern)原型模式(Prototype Pattern)结构型设计模式代理模式(Proxy)为其他对象提供一种代理以控制对该对象的访问 装饰模式(Decorator)动态地给一个对象添加一些额外的职责 适配器模式(Adapter)将一个类的接口变

14、换成客户端所期待的另一接口 组合模式(Composite)将对象组合成树形结构以表示“部分-整体”的层次结构 桥梁模式(Bridge)将抽象和实现解耦,使得两者可以独立的变化 外观模式(Facade)要求一个子系统的外部与其内部的通信必须通过一个统一的对象进行 享元模式(Flyweight)池技术的重要实现方式,使用共享对象可有效地支持大量的细粒度的对象 行为型设计模式-1模板方法模式(Template Method)定义一个操作中的算法的框架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤 命令模式(Command)将一个请求封装成一个对象,从而使用

15、不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能 责任链模式(Chain of Responsibility)使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止 策略模式(Strategy)定义一组算法,将每个算法都封装起来,并且使它们之间可以互换 迭代器模式(Iterator)访问一个容器对象中的各个元素,而又不需要暴露该对象的内部细节 行为型设计模式-2中介者模式(Mediator)用一个中介对象封装一系列的对象交互,中介者使各对象不需要显示的相互作用,从而使其耦合松

16、散,而且可以独立的改变他们之间的交互 观察者模式(Observer)定义对象间的一种一对多的依赖关系,使得每当一个对象改变状态,则所有依赖于它的对象都会得到通知并被自动更新责任链备忘录模式(Memento)在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态 访问者模式(Visitor)封装一些作用于某种数据结构中的各元素的操作,它可以在不改变数据结构的前提下定义作用于这些元素的新的操作 状态模式(State)当一个对象内在状态改变时允许其改变行为 解释器模式(Interpreter)给定一门语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该文法表示来解释语言

17、中的句子 GOF DPs in JDKAbstract 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

18、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.XPathFactory#newIn

19、stance().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.ByteBuffer#put()(also

20、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()(overrideable in all subclasses)

21、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 creational methods returning a different insta

22、nce 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.Desktop#getDesktop()Structural patternsAdapter(r

23、ecognizeable 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)(returns a Reader)java.io.OutputStreamWriter(OutputStre

24、am)(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/interface type which delegates/uses the given instance)None co

25、mes 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 however comes close.Composite(recognizeable by behavioral methods tak

26、ing 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(recognizeable by creational methods taking an instance of same abstract/interface type w

27、hich 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 unmodifiableXXX()methods.javax.servlet.http.HttpServletRequestWrapper and HttpServletResp

28、onseWrapper 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 abstract/interface types LifeCycle,ViewHandler,NavigationHandler and many more without that th

29、e enduser has to worry about it(which are however overrideable by injection).javax.faces.context.ExternalContext,which internally uses ServletContext,HttpSession,HttpServletRequest,HttpServletResponse,etc.Flyweight(recognizeable by creational methods returning a cached instance,a bit the multiton id

30、ea)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/interface type which in turn delegates/uses a different implementation of given abstract/interface type)java.lang.r

31、eflect.Proxy java.rmi.*,the whole API actually.Behavioral patternsChain of responsibility(recognizeable by behavioral methods which(indirectly)invokes the same method in another implementation of same abstract/interface type in a queue)java.util.logging.Logger#log()javax.servlet.Filter#doFilter()Com

32、mand(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 encapsulated by the command implementation during its creation)All implementations of java.lang.Runnable All implementations of jav

33、ax.swing.Action Interpreter(recognizeable by behavioral methods returning a structurally different instance/type of the given instance/type;note that parsing/formatting is not part of the pattern,determining the pattern and how to apply it is)java.util.Pattern java.text.Normalizer All subclasses of

34、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 implementations of java.util.Iterator(thus among others also java.util.Scanner!).All implementations of java.util.Enumeration Medi

35、ator(recognizeable by behavioral methods taking an instance of different abstract/interface type(usually using the command pattern)which delegates/uses the given instance)java.util.Timer(all scheduleXXX()methods)java.util.concurrent.Executor#execute()java.util.concurrent.ExecutorService(the invokeXX

36、X()and submit()methods)java.util.concurrent.ScheduledExecutorService(all scheduleXXX()methods)java.lang.reflect.Method#invoke()Memento(recognizeable by behavioral methods which internally changes the state of the whole instance)java.util.Date(the setter methods do that,Date is internally represented

37、 by a long value)All implementations of java.io.Serializable All implementations of ponent.StateHolder Observer(or Publish/Subscribe)(recognizeable by behavioral methods which invokes a method on an instance of another abstract/interface type,depending on own state)java.util.Observer/java.util.Obser

38、vable(rarely used in real world though)All implementations of java.util.EventListener(practically all over Swing thus)javax.servlet.http.HttpSessionBindingListener javax.servlet.http.HttpSessionAttributeListener javax.faces.event.PhaseListener State(recognizeable by behavioral methods which changes

39、its behaviour depending on the instances state which can be controlled externally)javax.faces.lifecycle.LifeCycle#execute()(controlled by FacesServlet,the behaviour is dependent on current phase(state)of JSF lifecycle)Strategy(recognizeable by behavioral methods in an abstract/interface type which i

40、nvokes a method in an implementation of a different abstract/interface type which has been passed-in as method argument into the strategy implementation)java.util.Comparator#compare(),executed by among others Collections#sort().javax.servlet.http.HttpServlet,the service()and all doXXX()methods take

41、HttpServletRequest and HttpServletResponse and the implementor has to process them(and not to get hold of them as instance variables!).javax.servlet.Filter#doFilter()Template method(recognizeable by behavioral methods which already have a default behaviour definied by an abstract type)All non-abstra

42、ct methods of java.io.InputStream,java.io.OutputStream,java.io.Reader and java.io.Writer.All non-abstract methods of java.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 th

43、e response.Youre free to implement none or any of them.Visitor(recognizeable by two different abstract/interface 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.

44、lang.model.element.AnnotationValue and AnnotationValueVisitor javax.lang.model.element.Element and ElementVisitor javax.lang.model.type.TypeMirror and TypeVisitor 小结设计一个模式的过程就是将问题抽象化,忽略不重要的细节后发现问题的本质,并找到普遍适用的解决方案的过程GoF的设计模式提供了一套可复用的面向对象技术设计模式起源于建筑设计学设计模式的基本要素是:名字、问题、初始环境、举例、末态环境、推理、其他有关模式、已知应用设计模式主要

45、有23种,可以将这些模式划分为三大类型:创建型、结构型和行为型创建型包括:单例模式、工厂方法模式、抽象工厂模式、建造者模式和原型模式结构型包括:代理模式、装饰模式、适配器模式、组合模式、桥梁模式、外观模式和享元模式行为型包括:模板方法模式、命令模式、责任链模式、策略模式、迭代器模式、中介者模式、观察者模式、备忘录模式、访问者模式、状态模式和解释器模式UML类图简介类图(Class Diagram):类图是面向对象系统建模中最常用和最重要的图,是定义其它图的基础。类图主要是用来显示系统中的类、接口以及它们之间的静态结构和关系的一种静态模型。类图的3个基本组件:类名、属性、方法。UML 1Key:

46、+means public visibility#means protected visibility-means private visibility means default(package)visibilitystatic variables are underlinedName of the classVariables optionalMethodsCardcardId:int-copy:boolean=falseconstructor Card(int id)+isKind(desiredKind:int)+isSharable():boolean+toString():Stri

47、ngExample:UML 2ABClass Bextendsclass ACD1.4Class Ccontains 1 to 4 objectsof class DFactoryProductcreatesOther kinds ofrelationsABClass Bimplementsinterface A泛化(generalization)泛化(generalization):表示is-a的关系,是对象之间耦合度最大的一种关系,子类继承父类的所有细节。直接使用语言中的继承表达。在类图中使用带三角箭头的实线表示,箭头从子类指向父类。实现(Realization)实现(Realizatio

48、n):在类图中就是接口和实现的关系。这个没什么好讲的。在类图中使用带三角箭头的虚线表示,箭头从实现类指向接口。依赖(Dependency)依赖(Dependency):对象之间最弱的一种关联方式,是临时性的关联。代码中一般指由局部变量、函数参数、返回值建立的对于其他对象的调用关系。一个类调用被依赖类中的某些方法而得以完成这个类的一些职责。在类图使用带箭头的虚线表示,箭头从使用类指向被依赖的类。关联(Association)关联(Association):对象之间一种引用关系,比如客户类与订单类之间的关系。这种关系通常使用类的属性表达。关联又分为一般关联、聚合关联与组合关联。后两种在后面分析。在

49、类图使用带箭头的实线表示,箭头从使用类指向被关联的类。可以是单向和双向。聚合(Aggregation)聚合(Aggregation):表示has-a的关系,是一种不稳定的包含关系。较强于一般关联,有整体与局部的关系,并且没有了整体,局部也可单独存在。如公司和员工的关系,公司包含 员工,但如果公司倒闭,员工依然可以换公司。在类图使用空心的菱形表示,菱形从局部指向整体。组合(Composition)组合(Composition):表示contains-a的关系,是一种强烈的包含关系。组合类负责被组合类的生命周期。是一种更强的聚合关系。部分不能脱离整体存在。如公司和部门的关 系,没有了公司,部门也不能存在了;调查问卷中问题和选项的关系;订单和订单选项的关系。在类图使用实心的菱形表示,菱形从局部指向整体。多重性(Multiplicity)多重性(Multiplicity):通常在关联、聚合、组合中使用。就是代表有多少个关联对象存在。使用数字.星号(数字)表示。如下图,一个割接通知可以关联0个到N个故障单。

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 应用文书 > 财经金融

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁