《lexi设计案例分析.ppt》由会员分享,可在线阅读,更多相关《lexi设计案例分析.ppt(76页珍藏版)》请在课桌文档上搜索。
1、1,第2章 实例研究:Lexi 文档编辑器,A WYSIWYG document editor.Mix text and graphics freely in various formatting styles.The usualPull-down menusScroll barsPage icons for jumping around the document.通过本实例设计,学习设计模式的实际应用,2,2.1 设计问题,Lexi设计的7个问题1 文档结构:对文档内部表示的选择几乎影响Lexi设计的每个方面。2 格式化3 修饰用户界面4 支持多种视感标准5 支持多种窗口系统6 用户操作7
2、拼写检查上述每个问题都有一组相关联的目标集合和限制条件集合。,3,2.2 文档结构,目标保持文档的物理结构。即将文本和图形安排到行、列和表等。可视化生成和显示文档。根据显示位置来映射文档内部表示的元素。限制条件应该一致地对待文本和图形。应该一致地对待简单元素和复合元素。但文本分析依赖于被分析对象的类型。,4,解决方案:递归组合,递归组合:Building more complex elements out of simpler ones.行列(段落)页(P24 第2段第2行)第5行第2列的第10个元素 The tenth element in line five of column two,隐
3、含:Each object type needs a corresponding classAll must have compatible interfaces(inheritance),图2 包含正文和图形的递归组合,图3 递归组合的对象结构,5,Glyph(图元类),Base class for composable graphical objectsAn Abstract class for all objects that can appear in a document.Both primitive and composed.,子类:Character,Image,Space,Ro
4、w,Column,6,图元类层次,Note the inherent recursion in this hierarchyi.e.,a Row is a Glyph&a Row also has Glyphs!,7,Glyph Interface and responsibilities,Glyphs know how to draw themselvesGlyphs know what space they occupyGlyphs know their children and parents,public abstract class Glyph/appearance public a
5、bstract void draw(Window w);public abstract Rect getBounds();/hit detection public abstract boolean intersects(Point);/structure public abstract void insert(Glyph g,int i);public abstract void remove(Glyph g);public abstract Glyph child(int i);public abstract Glyph parent();,8,COMPOSITE 模式 object st
6、ructural,意图treat individual objects&multiple,recursively-composed objects uniformly适用objects must be composed recursively,and no distinction between individual&composed elements,and objects in structure can be treated uniformly,Structure,9,COMPOSITE 模式(contd)object structural,效果uniformity:treat comp
7、onents the same regardless of complexityextensibility:new Component subclasses work wherever old ones do实现do Components know their parents?保持从子部件到父部件的引用能简化组合结构的遍历和管理uniform interface for both leaves&composites?最大化Component接口dont allocate storage for children in Component base classresponsibility for
8、 deleting children由Composite负责删除其子节点,10,2.3 格式化,格式化:将一个图元集合分解为若干行目标:自动换行Breaking up a document into lines.Many different algorithmstrade off quality for speedComplex algorithms限制条件Want to keep the formatting algorithm well-encapsulated.independent of the document structurecan add formatting algorith
9、m without modifying Glyphscan add Glyphs without modifying the formatting algorithm.Want to make it dynamically changeable.,11,Composition&Compositor,Compositorbase class abstracts linebreaking algorithmsubclasses for specialized algorithms,e.g.,SimpleCompositor,TeXCompositor接口格式化内容:void SetComposit
10、ion(Composition*)格式化:virtual void Compose()Compositioncomposite glyphsupplied a compositor&leaf glyphscreates row-column structure as directed by compositor,12,Composition&Compositor,一个未格式化的Composition对象只包含组成文档基本内容的可见图元,它并不包含像行和列这样决定文档物理结构的图元。Composite对象只在刚被创建并以待格式化的图元进行初始化后的状态当Composition对象需要格式化时,调
11、用它的Compositor的Compose操作。Compositor依次遍历Composition的各个图元,根据分行算法插入新的行和列图元。,Generated in accordance with compositor strategies&do not affect contents of leaf glyphs,13,Compositor&Composition,Compositor class will encapsulate a formatting algorithm.,Strategy,14,Compositor&Composition,分行算法封装能增加新的Composito
12、r子类而不触及Glyph类可在运行时刻改变分行算法在Composition接口中增加一个SetCompositor操作,15,STRATEGY模式 object behavioral,意图define a family of algorithms,encapsulate each one,&make them interchangeable to let clients&algorithms vary independently适用性when an object should be configurable with one of many algorithms,and all algorit
13、hms can be encapsulated,and one interface covers all encapsulations,结构,16,STRATEGY模式(contd)object behavioral,效果greater flexibility,reusecan change algorithms dynamicallystrategy creation&communication overheadinflexible Strategy interfacesemantic incompatibility of multiple strategies used together实
14、现exchanging information between a Strategy&its contextstatic strategy selection via templates,17,2.4 修饰用户界面,Wish to add visible borders and scroll-bars around pages.Inheritance is one way to do it.leads to class proliferationBorderedComposition,ScrollableComposition,BorderedScrollableCompositioninfl
15、exible at run-timeWill have classesBorderScrollerThey will be Glyphsthey are visibleclients shouldnt care if a page has a border or notThey will be composed.but in what order?,18,2.4 修饰用户界面,目标:add a frame around text compositionadd scrolling capability限制条件:embellishments should be reusable without s
16、ubclassing,i.e.,so they can be added dynamically at runtimeshould go unnoticed by clients,19,解决方案:“Transparent”Enclosure(透明围栏),Monoglyph:起修饰作用的图元的抽象类base class for glyphs having one childoperations on MonoGlyph pass through to childMonoGlyph subclasses:Frame:adds a border of specified widthScroller:
17、scrolls/clips child,adds scrollbars,20,MonoGlyph,Border calls MonoGlyph.draw();drawBorder();,Decorator,21,Transparent Enclosure,single-child compositioncompatible interfacesEnclosure will delegate operations to single child,but canadd stateaugment by doing work before or after delegating to the chil
18、d.,22,DECORATOR 模式 object structural,意图augment One object with new responsibilities适用性when extension by subclassing is impracticalfor responsibilities that can be withdrawn,Structure,23,DECORATOR模式(contd)object structural,效果responsibilities can be added/removed at run-timeavoids subclass explosionre
19、cursive nesting allows multiple responsibilities实现interface conformanceuse a lightweight,abstract base class for Decorator,24,2.5 支持多种视感标准,Want the application to be portable across diverse user interface libraries.Every user interface element will be a Glyph.Some will delegate to appropriate platfo
20、rm-specific operations.,25,Multiple Look&Feels,目标:support multiple look&feel standardsgeneric,Motif,Swing,PM,Macintosh,Windows,.extensible for future standards限制条件:dont recode existing widgets or clientsswitch look&feel without recompiling,26,解决方案:Abstract Object Creation,Instead ofScrollbar*sb=new
21、MotifScrollbar();useScrollbar*sb=factory-createScrollbar();where factory is an instance of MotifFactorythis begs the question of who created the factory!,27,Factory Interface,defines“manufacturing interface”subclasses produce specific productssubclass instance chosen at run-time,/This class is essen
22、tially a Java interfaceclass Factory public:Scrollbar*createScrollbar()=0;Menu*createMenu()=0;.;,28,Object Factories,Usual method:ScrollBar sb=new MotifScrollBar();Factory method:ScrollBar sb=guiFactory.createScrollBar();,29,Product Objects,The output of a factory is a product.,abstract,concrete,Abs
23、tract Factory,30,Building the Factory,If known at compile time(e.g.,Lexi v1.0 only Motif implemented).GUIFactory guiFactory=new MotifFactory();Set at startup(Lexi v2.0)String LandF=appProps.getProperty(LandF);GUIFactory guiFactory;if(LandF.equals(Motif)guiFactory=new MotifFactory();.Changeable by a
24、menu command(Lexi v3.0)re-initialize guiFactoryre-build the UI,Singleton,31,ABSTRACT FACTORY 模式 object creational,意图create families of related objects without specifying class names适用性when clients cannot anticipate groups of classes to instantiate,Structure,32,ABSTRACT FACTORY模式(contd)object creatio
25、nal,效果flexibility:removes type dependencies from clientsabstraction:hides products compositionhard to extend factory interface to create new products实现parameterization as a way of controlling interface sizeconfiguration with Prototypes,i.e.,determines who creates the factories,33,2.6 支持多种窗口系统,目标:mak
26、e composition appear in a windowsupport multiple window systems限制条件:minimize window system dependencies in application&framework code,34,2.6 支持多种窗口系统,是否可以用 Abstract Factory模式?Each GUI library will define its own concrete classes.无法给每种窗口组件都创建一个公共抽象产品类Start with an abstract Window hierarchyuser-level
27、window abstractiondisplays a glyph(structure)window system-independenttask-related subclasses(e.g.,IconWindow,PopupWindow),35,class Window public:.void iconify();/window-management void raise();.void drawLine(.);/device-independent void drawText(.);/graphics interface.;,Window Interface,36,Window 实现
28、,Defined interface Lexi deals with,but where does the real windowing library come into it?Could define alternate Window classes&subclasses.At build time can substitute the appropriate oneCould subclass the Window hierarchy.,Bridge,37,Window 实现代码示例,public class Rectangle extends Glyph public void dra
29、w(Window w)w.drawRect(x0,y0,x1,y1);.public class Window public void drawRect(Coord x0,y0,x1,y1)imp.drawRect(x0,y0,x1,y1);.public class XWindowImp extends WindowImp public void drawRect(Coord x0,y0,x1,y1).XDrawRectangle(display,windowId,graphics,x,y,w,h);,38,配置 imp,public abstract class WindowSystemF
30、actory public abstract WindowImp createWindowImp();public abstract ColorImp createColorImp();.public class XWindowSystemFactory extends WindowSystemFactory public WIndowImp createWindowImp()return new XWindowImp();.public class Window Window()imp=windowSystemFactory.createWindowImp();.,Abstract Fact
31、ory,well-known object,39,对象结构,Note:the decoupling between the logical structure of the contents in a window from the physical rendering of the contents in the window,40,BRIDGE 模式 object structural,意图separate a(logical)abstraction interface from its(physical)implementation(s)适用性when interface&impleme
32、ntation should vary independentlyrequire a uniform interface to interchangeable class hierarchies,Structure,41,BRIDGE 模式(contd)object structural,效果abstraction interface&implementation are independentimplementations can vary dynamicallyone-size-fits-all Abstraction&Implementor interfaces实现sharing Imp
33、lementors&reference countingcreating the right implementor,42,2.7 用户操作,Operationscreate new,save,cut,paste,quit,UI mechanismsmousing&typing in the documentpull-down menus,pop-up menus,buttons,kbd accelerators,Wish to de-couple operations from UI mechanismre-use same mechanism for many operationsre-u
34、se same operation by many mechanismsOperations have many different classeswish to de-couple knowledge of these classes from the UIWish to support multi-level undo and redo,43,Commands,A button or a pull-down menu is just a Glyph.but have actions command associated with user inpute.g.,MenuItem extend
35、s Glyph,Button extends Glyph,CouldPageFwdMenuItem extends MenuItemPageFwdButton extends ButtonCouldHave a MenuItem attribute which is a function call.没有强调撤销/重做操作很难将状态和函数联系起来函数很难扩充,并且很难部分复用。WillHave a MenuItem attribute which is a command object.,44,Command:Encapsulate Each Request,A Command encapsul
36、ates,Command mayimplement the operations itself,ordelegate them to other object(s),an operation(execute()an inverse operation(unexecute()a operation for testing reversibility(boolean reversible()state for(un)doing the operation,45,Command 类层次,Command is an abstract class for issuing requests.,46,Men
37、uItem与Command 之间的关系,void MenuItem:clicked()command-execute();,void PasteCommand:execute()/do the pastevoid CopyCommand:execute()/do the copy,47,Invoking Commands,When an interactive Glyph is tickled,it calls the Command object with which it has been initialized.,Command,48,Undo/Redo,Add an unexecute
38、()method to CommandReverses the effects of a preceding execute()operation using whatever undo information execute()stored into the Command object.Add a isUndoable()and a hadnoEffect()methodMaintain Command history:,49,COMMAND模式 object behavioral,意图encapsulate the request for a service适用性to parameter
39、ize objects with an action to performfor multilevel undo/redo,Structure,50,COMMAND模式(contd)object behavioral,效果abstracts executor of a servicesupports arbitrary-level undo-redocomposition yields macro-commandsmight result in lots of trivial command subclasses,51,2.8 拼写检查和断字处理,Textual analysischeckin
40、g for misspellingsintroducing hyphenation points where needed for good formatting.Want to support multiple algorithms.Want to make it easy to add new algorithms.Want to make it easy to add new types of textual analysisword countgrammarLegibility(易读性)Wish to de-couple textual analysis from the Glyph
41、classes.,52,2.8 拼写检查和断字处理,目标:analyze text for spelling errorsintroduce potential hyphenation(断字)sites限制条件:support multiple algorithmsdont tightly couple algorithms with document structure,53,Accessing Scattered Information,Need to access the text letter-by-letter.Our design has text scattered all ov
42、er the Glyph hierarchy.Different Glyphs have different data structures for storing their children(lists,trees,arrays,).Sometimes need alternate access patterns:spell check:forwardsearch back:backwardsevaluating equations:inorder tree traversal,54,Encapsulating Access&Traversals,Could replace index-o
43、riented access(as shown before)by more general accessors that arent biased towards arrays.Glyph g=for(g.first(PREORDER);!g.done();g-next()Glyph current=g-getCurrent();Problems:cant support new traversals without extending enum and modifying all parent Glyph types.Cant re-use code to traverse other o
44、bject structures(e.g.,Command history).,55,解决方案:封装遍历,Iteratorencapsulates a traversal algorithm without exposing representation details to callers uses Glyphs child enumeration operationThis is an example of a“preorder iterator”,56,Iterator 层次,Iterator,57,Using Iterators,Glyph*g;Iterator*i=g-CreateI
45、terator();for(i-First();!i-IsDone();i-Next()Glyph*child=i-CurrentItem();/do something with current child,58,Initializing Iterators,Iterator*Row:CreateIterator()return new ListIterator(_children);,59,Implementing a Complex Iterator,void PreorderIterator:First()Iterator*i=_root-CreateIterator();if(i)i
46、-First();_iterators.RemoveAll();_iterators.Push(i);Glyph*PreorderIterator:CurrentItem()const return _iterators.Size()0?_iterators.Top()-CurrentItem():0;,60,Implementing a Complex Iterator(contd),void PreorderIterator:Next()Iterator*i=_iterators.Top()-CurrentItem()-CreateIterator();i-First();_iterato
47、rs.Push(i);while(_iterators.Size()0,61,ITERATOR模式 object behavioral,意图access elements of a container without exposing its representation适用性require multiple traversal algorithms over a containerrequire a uniform traversal interface over different containerswhen container classes&traversal algorithm m
48、ust vary independently,Structure,62,ITERATOR模式(contd)object behavioral,效果flexibility:aggregate&traversal are independentmultiple iterators&multiple traversal algorithmsadditional communication overhead between iterator&aggregate实现internal versus external iteratorsviolating the object structures enca
49、psulationrobust iterators,63,ITERATOR 模式(contd)object behavioral,int main(int argc,char*argv)vector args;for(int i=0;i:iterator i(args.begin();i!=args.end();i+)cout*i;cout endl;return 0;,Iterators are used heavily in the C+Standard Template Library(STL),The same iterator pattern can be applied to an
50、y STL container!,64,访问动作,Now that we can traverse,we need to add actions while traversing that have statespelling,hyphenation,Could augment the Iterator classesbut that would reduce their reusabilityCould augment the Glyph classesbut will need to change Glyph classes for each new analysisWill need t