1第2章实例研究:Lexi文档编辑器•AWYSIWYGdocumenteditor.•Mixtextandgraphicsfreelyinvariousformattingstyles.•Theusual–Pull-downmenus–Scrollbars–Pageiconsforjumpingaroundthedocument.•通过本实例设计,学习设计模式的实际应用22.1设计问题•Lexi设计的7个问题–1文档结构:对文档内部表示的选择几乎影响Lexi设计的每个方面。–2格式化–3修饰用户界面–4支持多种视感标准–5支持多种窗口系统–6用户操作–7拼写检查•上述每个问题都有一组相关联的目标集合和限制条件集合。32.2文档结构•目标–保持文档的物理结构。即将文本和图形安排到行、列和表等。–可视化生成和显示文档。–根据显示位置来映射文档内部表示的元素。•限制条件–应该一致地对待文本和图形。–应该一致地对待简单元素和复合元素。–但文本分析依赖于被分析对象的类型。4解决方案:递归组合•递归组合:Buildingmorecomplexelementsoutofsimplerones.–行——列(段落)——页–(P24第2段第2行)第5行第2列的第10个元素Thetenthelementinlinefiveofcolumntwo,•隐含:–Eachobjecttypeneedsacorrespondingclass–Allmusthavecompatibleinterfaces(inheritance)图2包含正文和图形的递归组合图3递归组合的对象结构5Glyph(图元类)BaseclassforcomposablegraphicalobjectsAnAbstractclassforallobjectsthatcanappearinadocument.–Bothprimitiveandcomposed.voidinsert(Glyph)voidremove(Glyph)Glyphchild(int)Glyphparent()管理子图元的接口booleanintersects(Coord,Coord)判断一个指定的点是否与图元相交voiddraw(Window*)VoidBounds(Rect)在窗口上表示自己返回图元占用的矩形面积操作任务基本接口:子类:Character,Image,Space,Row,Column6图元类层次Notetheinherentrecursioninthishierarchyi.e.,aRowisaGlyph&aRowalsohasGlyphs!7GlyphInterfaceandresponsibilities•Glyphsknowhowtodrawthemselves•Glyphsknowwhatspacetheyoccupy•GlyphsknowtheirchildrenandparentspublicabstractclassGlyph{//appearancepublicabstractvoiddraw(Windoww);publicabstractRectgetBounds();//hitdetectionpublicabstractbooleanintersects(Point);//structurepublicabstractvoidinsert(Glyphg,inti);publicabstractvoidremove(Glyphg);publicabstractGlyphchild(inti);publicabstractGlyphparent();}8COMPOSITE模式objectstructural意图treatindividualobjects&multiple,recursively-composedobjectsuniformly适用objectsmustbecomposedrecursively,andnodistinctionbetweenindividual&composedelements,andobjectsinstructurecanbetreateduniformlyStructure9COMPOSITE模式(cont’d)objectstructural效果+uniformity:treatcomponentsthesameregardlessofcomplexity+extensibility:newComponentsubclassesworkwhereveroldonesdo实现–doComponentsknowtheirparents?•保持从子部件到父部件的引用能简化组合结构的遍历和管理–uniforminterfaceforbothleaves&composites?•最大化Component接口–don’tallocatestorageforchildreninComponentbaseclass–responsibilityfordeletingchildren•由Composite负责删除其子节点102.3格式化•格式化:将一个图元集合分解为若干行•目标:自动换行–Breakingupadocumentintolines.•Manydifferentalgorithms•tradeoffqualityforspeed–Complexalgorithms•限制条件–Wanttokeeptheformattingalgorithmwell-encapsulated.•independentofthedocumentstructure–canaddformattingalgorithmwithoutmodifyingGlyphs–canaddGlyphswithoutmodifyingtheformattingalgorithm.–Wanttomakeitdynamicallychangeable.11Composition&CompositorCompositor–baseclassabstractslinebreakingalgorithm–subclassesforspecializedalgorithms,e.g.,SimpleCompositor,TeXCompositor–接口•格式化内容:voidSetComposition(Composition*)•格式化:virtualvoidCompose()Composition–compositeglyph–suppliedacompositor&leafglyphs–createsrow-columnstructureasdirectedb...