lexi设计案例分析

上传人:e****s 文档编号:241653137 上传时间:2024-07-13 格式:PPT 页数:76 大小:746KB
返回 下载 相关 举报
lexi设计案例分析_第1页
第1页 / 共76页
lexi设计案例分析_第2页
第2页 / 共76页
lexi设计案例分析_第3页
第3页 / 共76页
点击查看更多>>
资源描述
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.通过本实例设计,学习设计模式的实际应用22.1 设计问题Lexi设计的7个问题1 文档结构:对文档内部表示的选择几乎影响Lexi设计的每个方面。2 格式化3 修饰用户界面4 支持多种视感标准5 支持多种窗口系统6 用户操作7 拼写检查上述每个问题都有一组相关联的目标集合和限制条件集合。32.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,隐含:Each object type needs a corresponding classAll must have compatible interfaces(inheritance)图2 包含正文和图形的递归组合图3 递归组合的对象结构5Glyph 图元类Base class for composable graphical objectsAn Abstract class for all objects that can appear in a document.Both primitive and composed.void insert(Glyph)void remove(Glyph)Glyph child(int)Glyph parent()管理子图元的接口boolean intersects(Coord,Coord)判断一个指定的点是否与图元相交void draw(Window*)Void Bounds(Rect)在窗口上表示自己返回图元占用的矩形面积操作任务基本接口:子类:Character,Image,Space,Row,Column 6图元类层次Note the inherent recursion in this hierarchywi.e.,a Row is a Glyph&a Row also has Glyphs!7Glyph Interface and responsibilitiesGlyphs know how to draw themselvesGlyphs know what space they occupyGlyphs know their children and parentspublic abstract class Glyph /appearance public abstract 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();8COMPOSITE 模式 object structural意图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 uniformlyStructure9COMPOSITE 模式(contd)object structural效果+uniformity:treat components the same regardless of complexity+extensibility: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 deleting children由Composite负责删除其子节点102.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 algorithm without modifying Glyphscan add Glyphs without modifying the formatting algorithm.Want to make it dynamically changeable.11Composition&CompositorCompositorbase class abstracts linebreaking algorithmsubclasses for specialized algorithms,e.g.,SimpleCompositor,TeXCompositor接口接口格式化内容:格式化内容:void SetCompositionComposition*格式化:格式化:virtual void ComposeCompositioncomposite glyphsupplied a compositor&leaf glyphscreates row-column structure as directed by compositor12Composition&Compositor一个未格式化的Composition对象只包含组成文档根本内容的可见图元,它并不包含像行和列这样决定文档物理结构的图元。Composite对象只在刚被创立并以待格式化的图元进行初始化后的状态当Composition对象需要格式化时,调用它的Compositor的Compose操作。Compositor依次遍历Composition的各个图元,根据分行算法插入新的行和列图元。Generated in accordance with compositor strategies&do not affect contents of leaf glyphs13Compositor&CompositionCompositor class will encapsulate a formatting algorithm.14Compositor&Composition分行算法封装能增加新的Compositor子类而不触及Glyph类可在运行时刻改变分行算法在Composition接口中增加一个SetCompositor操作15STRATEGY模式 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 algorithms can be encapsulated,and one interface covers all encapsulations 结构16STRATEGY模式(contd)object behavioral效果+greater flexibility,reuse+can change algorithms dynamicallystrategy creation&communication overheadinflexible Strategy interfacesemantic incompatibility of multiple strategies used together实现exchanging information between a Strategy&its contextstatic strategy selection via templates172.4 修饰用户界面Wish to add visible borders and scroll-bars around pages.Inheritance is one way to do it.leads to class proliferationBorderedComposition,ScrollableComposition,BorderedScrollableCompositioninflexible 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?182.4 修饰用户界面目标:add a frame around text compositionadd scrolling capability限制条件:embellishments should be reusable without subclassing,i.e.,so they can be added dynamically at runtimeshould go unnoticed by clients19解决方案:“Transparent Enclosure透明围栏Monoglyph:起修饰作用的图元的抽象类:起修饰作用的图元的抽象类base class for glyphs having one childoperations on MonoGlyph pass through to childMonoGlyph subclasses:Frame:adds a border of specified widthScroller:scrolls/clips child,adds scrollbars20MonoGlyphBorder calls MonoGlyph.draw();drawBorder();21Transparent Enclosuresingle-child compositioncompatible interfacesEnclosure will delegate operations to single child,but canadd stateaugment by doing work before or after delegating to the child.22DECORATOR 模式 object structural意图augment One object with new responsibilities适用性when extension by subclassing is impracticalfor responsibilities that can be withdrawnStructure23DECORATOR模式(contd)object structural效果+responsibilities can be added/removed at run-time+avoids subclass explosion+recursive nesting allows multiple responsibilities实现interface conformanceuse a lightweight,abstract base class for Decorator242.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 platform-specific operations.25Multiple 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 recompiling26解决方案:Abstract Object CreationInstead ofScrollbar*sb=new MotifScrollbar();useScrollbar*sb=factory-createScrollbar();where factory is an instance of MotifFactorythis begs the question of who created the factory!27Factory Interfacedefines“manufacturing interfacesubclasses produce specific productssubclass instance chosen at run-time/This class is essentially a Java interfaceclass Factory public:Scrollbar*createScrollbar()=0;Menu*createMenu()=0;.;28Object FactoriesUsual method:ScrollBar sb=new MotifScrollBar();Factory method:ScrollBar sb=guiFactory.createScrollBar();29Product ObjectsThe output of a factory is a product.abstractconcrete30Building the FactoryIf 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 menu command(Lexi v3.0)re-initialize guiFactoryre-build the UI31ABSTRACT FACTORY 模式 object creational意图create families of related objects without specifying class names适用性when clients cannot anticipate groups of classes to instantiateStructure32ABSTRACT FACTORY模式(contd)object creational效果+flexibility:removes type dependencies from clients+abstraction: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 factories332.6 支持多种窗口系统目标:make composition appear in a windowsupport multiple window systems限制条件:minimize window system dependencies in application&framework code342.6 支持多种窗口系统是否可以用 Abstract Factory模式?Each GUI library will define its own concrete classes.无法给每种窗口组件都创立一个公共抽象产品类Start with an abstract Window hierarchyuser-level window abstractiondisplays a glyph(structure)window system-independenttask-related subclasses(e.g.,IconWindow,PopupWindow)35class Window public:.void iconify();/window-management void raise();.void drawLine(.);/device-independent void drawText(.);/graphics interface .;Window Interface36Window 实现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.37Window 实现代码例如public class Rectangle extends Glyph public void draw(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 WindowSystemFactory 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();.well-known object39对象结构Note:the decoupling between the logical structure of the contents in a window from the physical rendering of the contents in the window40BRIDGE 模式 object structural意图separate a(logical)abstraction interface from its(physical)implementation(s)适用性when interface&implementation should vary independentlyrequire a uniform interface to interchangeable class hierarchiesStructure41BRIDGE 模式(contd)object structural效果+abstraction interface&implementation are independent+implementations can vary dynamicallyone-size-fits-all Abstraction&Implementor interfaces实现sharing Implementors&reference countingcreating the right implementor422.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-use 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 redo43CommandsA button or a pull-down menu is just a Glyph.but have actions command associated with user inpute.g.,MenuItem extends 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.44Command:Encapsulate Each RequestA Command encapsulatesCommand maynimplement the operations itself,orndelegate them to other object(s)nan operation(execute()nan inverse operation(unexecute()na operation for testing reversibility(boolean reversible()nstate for(un)doing the operation45Command 类层次Command is an abstract class for issuing requests.46MenuItem与Command 之间的关系void MenuItem:clicked()command-execute();void PasteCommand:execute()/do the pastevoid CopyCommand:execute()/do the copy47Invoking CommandsWhen an interactive Glyph is tickled,it calls the Command object with which it has been initialized.48Undo/RedoAdd an unexecute()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:49COMMAND模式 object behavioral意图encapsulate the request for a service适用性to parameterize objects with an action to performfor multilevel undo/redoStructure50COMMAND模式(contd)object behavioral效果+abstracts executor of a service+supports arbitrary-level undo-redo+composition yields macro-commandsmight result in lots of trivial command subclasses512.8 拼写检查和断字处理Textual analysischecking 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 classes.522.8 拼写检查和断字处理目标:analyze text for spelling errorsintroduce potential hyphenation断字 sites限制条件:support multiple algorithmsdont tightly couple algorithms with document structure53Accessing Scattered InformationNeed to access the text letter-by-letter.Our design has text scattered all over 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 traversal54Encapsulating Access&TraversalsCould replace index-oriented 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 object 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 iterator56Iterator 层次57Using IteratorsGlyph*g;Iterator*i=g-CreateIterator();for(i-First();!i-IsDone();i-Next()Glyph*child=i-CurrentItem();/do something with current child 58Initializing IteratorsIterator*Row:CreateIterator()return new ListIterator(_children);59Implementing a Complex Iteratorvoid PreorderIterator:First()Iterator*i=_root-CreateIterator();if(i)i-First();_iterators.RemoveAll();_iterators.Push(i);Glyph*PreorderIterator:CurrentItem()const return _iterators.Size()0?_iterators.Top()-CurrentItem():0;60Implementing a Complex Iterator(contd)void PreorderIterator:Next()Iterator*i=_iterators.Top()-CurrentItem()-CreateIterator();i-First();_iterators.Push(i);while(_iterators.Size()0&_iterators.Top()-IsDone()delete _iterators.Pop();_iterators.Top()-Next();61ITERATOR模式 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 must vary independentlyStructure62ITERATOR模式(contd)object behavioral效果+flexibility:aggregate&traversal are independent+multiple iterators&multiple traversal algorithmsadditional communication overhead between iterator&aggregate实现internal versus external iteratorsviolating the object structures encapsulationrobust iterators63ITERATOR 模式(contd)object behavioralint main(int argc,char*argv)vector args;for(int i=0;i argc;i+)args.push_back(string(argvi);for(vector:iterator i(args.begin();i!=args.end();i+)cout *i;cout getChar();if(isalpha(c)currentWord+=c;else if(isMispelled(currentWord)/add misspelling to list misspelling.addElement(currentWord);currentWord=“;public Vector getMisspellings return misspellings;71Using SpellingVisitorPreorderIterator i=new PreorderIterator();i.setVisitor(new SpellingVisitor();i.visitAll(rootGlyph);Vector misspellings=(SpellingVisitor)i.getVisistor().getMisspellings();public class Iterator private Visitor v;public void visitAll(Glyph start)for(first();!isDone();next()currentItem().visit(v);72CharacterGlyph(a)CharacterGlyph(_)spell:SpellingVisitorVisitor Activity Diagramvisit(spell)visitCharacterGlyph(this)getChar()visitCharacterGlyph(this)getChar()visit(spell)getMisspellings()isMispelled(currentWord)73HyphenationVisitorVisit words,and then insert“discretionary hyphen Glyphs.74VISITOR模式 object behavioral意图centralize operations on an object structure so that they can vary independently but still behave polymorphically适用性when classes define many unrelated operationsclass relationships of objects in the structure rarely change,but the operations on them change oftenalgorithms keep state thats updated during traversalStructure75VISITOR模式(contd)object behavioral效果+flexibility:visitor&object structure are independent+localized functionality实现double dispatchgeneral interface to elements of object structure76总结In the design of LEXI,saw the following patterns.Compositerepresent physical structureStrategyto allow different formatting algorithmsDecoratorto embellish the UIAbstract Factoryfor supporting multiple L&F standardsBridgefor supporting multiple windowing platformsCommandfor undoable operationsIteratorfor traversing object structuresVisitorfor allowing open-ended analytical capabilities without complicating the document structure
展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 商业管理 > 商业计划


copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


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