Patterns: Visitor, Strategy, Chain, State, Command

Total Page:16

File Type:pdf, Size:1020Kb

Patterns: Visitor, Strategy, Chain, State, Command Software Architecture Bertrand Meyer Lecture 6: More patterns: Visitor, Strategy, Chain, State, Command Command 2 Command pattern - Intent Purpose Way to implement an undo-redo mechanism, e.g. in text editors. [OOSC, p 285-290] ”Way to encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undbldoable operations.” [Gamma et al., p 233] Application example EiffelStudio 3 1 The problem Enabling users of an interactive system to cancel the effect of the last command. Often implemented as “Control-Z”. Should support multi-level undo-redo, with no limitation other than a possible maximum set by the user A good review of O-O techniques 4 Working example: text editor Notion of “current line”. Assume commands such as: ¾ Insert line after current position ¾ Insert line before current position ¾ Delete current line ¾ Replace current line ¾ Swap current line wihith next if any ¾ ... This is a line-oriented view for simplicity, but the discussion applies to more sophisticated views 5 Underlying class (from “business model”) class EDIT_CONTROLLER feature text : LINKED_LIST [STRING] remove -- Remove line at current position. require not off do text.remove end put_right (line: STRING) -- Insert line after current position. require not after do text.put_right (line) end ... end 6 2 Key step in devising a software architecture Finding the right abstractions (Interesting object types) Here: The notion of “command” 7 Keeping the history of the session The history list: Insert Insert RemoveInsert Swap Oldest Most recent history : LINKED_LIST [COMMAND] 8 What’s a “command” object? An instance of COMMAND includes information about one execution of a command by the user, sufficient to: ¾ Execute the command ¾ Cancel the command if requested later For example, in a delete command object, we need: • The position of the line being deleted • The content of that line 9 3 General notion of command deferred class COMMAND feature done: BOOLEAN -- Has this command been executed? execute -- Carry out one execution of this command. deferred ensure: done already: done end undo -- Cancel an earlier execution of this command. require already: done deferred end end 10 Command class hierarchy execute* * undo* COMMAND * deferred + effective + + DELETION INSERTION … + execute+ execute + undo+ undo line index index ... ... 11 A command class (sketch, no contracts) class DELETION inherit COMMAND feature controller : EDIT_CONTROLLER -- Access to business model line : STRING -- Line being deleted index : INTEGER -- Position of line being deleted extxecute -- Remove current line and remember it. do line := controller.item ; index := controller.index controller.remove ; done := True end undo -- Re-insert previously removed line. do controller.go_ith (index) controller.put_left (line) end end 12 4 Executing a user command decode_user_request if “Request normal command” then “Create command object c corresponding to user request” history.extend (c) c.execute elseif “Request UNDO” then if not history.before then -- Ignore excessive requests history. item. undo history.back end Insert Insert Remove Insert elseif “Request REDO” then history.is_last if not then -- Ignore excessive requests item history.forth history.item.execute end end 13 Command pattern: overall architecture history commands * APPLICATION HISTORY COMMAND execute* execute undo* can_undo, can_redo redo* undo, redo undo_all, redo_all extend + + COMMAND_1 COMMAND_2 execute+ execute+ undo+ undo+ redo+ redo+ 14 The undo-redo pattern Has been extensively used Fairly easy to implement Details must be handled carefully (e.g. some commands may not be undoable) Elegant use of O-O techniques Disadvantaggpe: explosion of small classes In Java, can use “inner” classes. 15 5 Using agents For each user command, have two routines: ¾ The routine to do it ¾ The routine to undo it! 16 The history list using agents The history list simply becomes a list of agents pairs: history : LINKED_LIST [TUPLE [PROCEDURE [ANY, TUPLE], PROCEDURE [ANY, TUPLE]] Basic scheme remains the same, but no need for command objects any more; the his tory lis t s imp ly con ta ins agen ts. Insert Insert RemoveInsert Swap De- De- Re-insertDe- Swap insert insert insert 17 Executing a user command (before) decode_user_request if “Request is normal command” then “Create command object c corresponding to user request” history.extend (c) c.execute elseif “Request is UNDO” then if not history.before then -- Ignore excessive requests history item undo . Insert Insert Remove Insert history.back end item elseif “Request is REDO” then if not history.is_last then -- Ignore excessive requests history.forth history. item.execute end end 18 6 Executing a user command (now) “Decode user_request giving two agents do_it and undo_it ” if “Request is normal command” then history.extend ([do_it, undo_it ]) Insert Insert Remove Swap do_it.call ([]) De- De- Re- Swap elseif “Request is UNDO” then insert insert insert if not history.before then history.item.item (2) .call ([]) history.back end elseif “Request is REDO” then if not history.is_last then history.forth history.item.item (1) .call ([]) end 19 end Command - Consequences Command decouples the object that invokes the operation from the one that knows how to perform it. Commands are first-class objects. They can be manipulated and extended like any other object. You can assemble commands into a composite command. It's easy to add new Commands, because you don't have to change existing classes. 20 Command - Participants Command declares an interface for executing an operation. Concrete command ¾ defines a binding between a Receiver object and an action. ¾ implements Execute by invoking the corresponding operation(s) on Receiver. Client creates a ConcreteCommand object and sets its receiver. Invoker asks the command to carry out the request. Receiver knows how to perform the operations associated with carrying out a request. Any class may serve as a Receiver. 21 7 Some design patterns Creational Behavioral ¾ Abstract Factory ¾ Chain of Responsibility ¾ Builder ¾ Command (undo/redo) ¾ Factory Method ¾ Interpreter ¾ Prototype ¾ Iterator ¾ Singleton ¾ Mediator ¾ Memento Structural ¾ Observer ¾ Adapter ¾ State ¾ Bridge ¾ Strategy ¾ Composite ¾ Template Method ¾ Decorator ¾ Visitor ¾ Façade ¾ Flyweight ¾ Proxy Visitor 23 Visitor - Intent “Represents an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.” [Gamma et al., p 331] ¾ Static class hierarchy ¾ Need to perform traversal operations on corresponding data structures ¾ Avoid changing the original class structure 24 8 Visitor application example Set of classes to deal with an Eiffel or Java program (in EiffelStudio, Eclipse ...) Or: Set of classes to deal with XML documents (XML_NODE, XML_DOCUMENT, XML_ELEMENT, XML_ATTRIBUTE, XML_CONTENT…) One parser (or several: keep comments or not…) Many forma tters: ¾ Pretty-print ¾ Compress ¾ Convert to different encoding ¾ Generate documentation ¾ Refactor ¾ … 25 Inheritance hierarchy center * * display* FIGURE rotate* * * OPEN_ perimeter * CLOSED_ FIGURE FIGURE + perimeter + + perimeter SEGMENT POLYLINE POLYGON + ELLIPSE ... ... side1 RECTANGLE side2 TRIANGLE diagonal perimeter ++ * deferred perimeter ++ + effective SQUARE CIRCLE ++ ++ redefined perimeter 26 Polymorphic data structures (POLYGON) (CIRCLE) (CIRCLE) (ELLIPSE) (POLYGON) figs : LIST [FIGURE ] from figs zstart until figs zafter loop figs zitem z display figs zforth end 27 9 The dirty secret of O-O architecture center * * display* FIGURE rotate* Is it easy to add types (e.g. LOZENGE) to existing operations * * OPEN_ perimeter * CLOSED_ FIGURE FIGURE perimeter + perimeter + + SEGMENT POLYLINE POLYGON + ELLIPSE ++ ... ... perimeter side1 RECTANGLE side2 TRIANGLE diagonal ++ perimeter SQUARE CIRCLE perimeter ++ What about the reverse: adding an operation to existing types? Vehicle example * VEHICLE + + TAXI BUS We want to add external functionality, for example: Maintenance Schedule a vehicle for a particular day 29 Vehicle operations Why is this approach bad ? maintain (v : VEHICLE) schedule (v : VEHICLE, d: DAY) -- Perform maintenance on v. -- Set up schedule of v for d. require require exists: v /= Void exists: v /= Void do do if attached {BUS } v as b then if attached {BUS } v as b then b zsend_to_depot b zschedule (d ) end end if attached {TAXI } v as t then if attached {TAXI } v as t then t zsend_to_garage t zput_on_call (d ) (Next_monday) end end ... Other cases ... ... Other cases ... end end end end 30 10 The original view CLIENT visit T_TARGET Client (calls) 31 Visitor participants Target classes Example: BUS, TAXI Client classes Application classes that need to perform operations on target objects Visitor classes Written only to smooth out the collaboration between the other two 32 Visitor participants Visitor General notion of visitor Concrete visitor Specific visit operation, applicable to all target elements Target General notion of visitable element Concrete target Specific visitable element 33 11 The original view CLIENT visit T_TARGET Client (calls) The visitor ballet CLIENT t zaccept (v ) v T_TARGET V_VISITOR v zT_visit (Current ) Client Client (calls) (knows about) Visitor class hierarchies accept* v zT_visit (Current ) * * visit_bus* VISITOR VEHICLE visit_tram* + + + + TAXI BUS MAINTENANCE SCHEDULE _VISITOR _VISITOR accept+ accept+ visit_taxi + visit_taxi
Recommended publications
  • 1 Design Pattern for Open Class (DRAFT) 2 Abstract Factory
    1 Design Pattern for Open Class (DRAFT) Tanaka Akira <[email protected]> A design pattern describes a software architecture which is reusable and exten- sible. [GoF] is the book containing 23 design patterns for OOP languages like C++ and Java. [GoF] describes several trade offs of the patterns. In C++ and Java, a class is defined by only one module. However, there are languages which can define a class by two or more modules: Cecil, MultiJava, AspectJ, MixJuice, CLOS, Ruby, etc. Such class is called "open class" because it is extensible by modules implemented later [Chambers]. For languages with open class, more extensible and/or simpler design patterns exists. We studied design patterns with open class for each GoF design patterns. In this paper, we describe two patterns: the Abstract Factory pattern and the Visitor pattern. 2 Abstract Factory The Abstract Factory pattern is a design pattern for separating class names from the code which generates the object group of related classes for making them configurable. Following figure is the class diagram of the Abstract Factory pattern. Since the example described in [GoF] uses only one concrete factory for each binaries, the required concrete factory is selected statically. The example builds two binaries for Motif and Presentation Manager from a single source code. Two concrete factories are exist for Motif and Presentation Manager. When a binary is built, it is selected which concrete factory is linked. Such static selection can be implemented with the fewer number of classes by open class as following modules. • The module which defines Window and ScrollBar class and their methods which is independent to window systems.
    [Show full text]
  • The Command Dispatcher Pattern Benoit Dupire and Eduardo B Fernandez {[email protected], [email protected]}
    The Command Dispatcher Pattern Benoit Dupire and Eduardo B Fernandez {[email protected], [email protected]} Department of Computer Science and Engineering. Florida Atlantic University Boca Raton, FL 33431 Can also be called: Command Evaluator Pattern. Intent This pattern increases the flexibility of applications by enabling their services to be changed, by adding, replacing or removing any command handlers at any point in time without having to modify, recompile or statically relink the application. By simulating the command-evaluation feature common in interpreted languages, this pattern supports the need for continual, incremental evolution of applications. Example Autonomous Underwater Vehicles (AUVs) are small, unmanned, untethered submersibles. There are numerous applications for AUVs, such as oceanographic surveys, operations in hazardous environments, underwater structure inspection and military operations. We implement the high level controller of this AUV as a Hierarchical Finite State Machine (Figure 1). A state of the Finite State Machine (FSM) represents a mode of the system, in which some tasks have to be executed, as described in the mission plan. The system takes transitions based on the results of these actions and the progression of the AUV. The system is programmed with high-level commands of the style "set depth 3" state1 state2 action 1.1 action 2.1 Figure 1: Simplified Finite State Machine for the AUV. The FSM must be able to fire any type of actions, without knowing anything about them. This problem is addressed by the Command Pattern [GOF95], which encapsulates an action as an object, thereby letting you parameterize clients with different actions.
    [Show full text]
  • Tree Visitors in Clojure Update the Java Visitor Pattern with Functional Zippers
    Tree visitors in Clojure Update the Java Visitor pattern with functional zippers Skill Level: Intermediate Alex Miller ([email protected]) Senior Engineer Revelytix 20 Sep 2011 JVM language explorer Alex Miller has recently discovered the benefits of implementing the Visitor pattern using Clojure, a functional Lisp variant for the Java Virtual Machine. In this article, he revisits the Visitor pattern, first demonstrating its use in traversing tree data in Java programs, then rewriting it with the addition of Clojure's functional zippers. I’ve used trees of domain objects in my Java applications for many years. More recently, I’ve been using them in Clojure. In each case, I've found that the Visitor pattern is a reliable tool for manipulating trees of data. But there are differences in how the pattern works in a functional versus object-oriented language, and in the results it yields. About Clojure Clojure is a dynamic and functional programming language variant of Lisp, written specifically for the JVM. Learn more about Clojure on developerWorks: •"The Clojure programming language" •"Clojure and concurrency" •"Solving the Expression Problem with Clojure 1.2" •"Using CouchDB with Clojure" In this article, I revisit domain trees and the Visitor pattern for the Java language, Tree visitors in Clojure Trademarks © Copyright IBM Corporation 2011 Page 1 of 27 developerWorks® ibm.com/developerWorks then walk through several visitor implementations using Clojure. Being a functional language, Clojure brings new tricks to data query and manipulation. In particular, I've found that integrating functional zippers into the Visitor pattern yields efficiency benefits, which I explore.
    [Show full text]
  • Enterprise Development with Flex
    Enterprise Development with Flex Enterprise Development with Flex Yakov Fain, Victor Rasputnis, and Anatole Tartakovsky Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo Enterprise Development with Flex by Yakov Fain, Victor Rasputnis, and Anatole Tartakovsky Copyright © 2010 Yakov Fain, Victor Rasputnis, and Anatole Tartakovsky.. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected]. Editor: Mary E. Treseler Indexer: Ellen Troutman Development Editor: Linda Laflamme Cover Designer: Karen Montgomery Production Editor: Adam Zaremba Interior Designer: David Futato Copyeditor: Nancy Kotary Illustrator: Robert Romano Proofreader: Sada Preisch Printing History: March 2010: First Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Enterprise Development with Flex, the image of red-crested wood-quails, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein.
    [Show full text]
  • Facet: a Pattern for Dynamic Interfaces
    Facet: A pattern for dynamic interfaces Author: Eric Crahen SUNY at Buffalo CSE Department Amherst, NY 14260 201 Bell Hall 716-645-3180 <[email protected]> Context: Wherever it is desirable to create a context sensitive interface in order to modify or control the apparent behavior if an object. Problem: How can I modify the behavior of an existing object so that different behaviors are shown under different circumstances; and yet still maintain a clean separation between the policy (when each behavior is available) and implementation of each behavior allowing them to be developed independently of one another? Forces: Interfaces provide an essential level of abstraction to object oriented programming. Generally, objects are able define aspects of their function very well using interfaces. At times, this may not be enough. When dealing with two or more classes whose responsibilities are distinctly separate, but whose behavior is closely related, classes can begin to resist modularization. For example, adding security to an application means inserting code that performs security checks into numerous locations in existing classes. Clearly, these responsibilities are distinct; the original classes being responsible for the tasks they were designed to perform, and the security classes being responsible for providing access control. However, making those original classes secure means intermingling code that deals with security. When the classes dealing with security are changed many classes are going to be impacted. One method of adding new behavior to an existing class might be to simply create a subclass and embed that new behavior. In the security example, this would mean creating a subclass for each class that needs to be secure and adding calls to the security code.
    [Show full text]
  • Object-Oriented Desgin Visitor Pattern George Blankenship 1
    Object-Oriented Desgin Visitor Pattern CSCI 253 Object Oriented Design: Visitor Pattern George Blankenship Visitor Pattern George Blankenship 1 Overview Creational Patterns Structural Patterns Behavioral Patterns Singleton Composite Chain of Respons. Abstract factory Façade Command Factory Method Proxy Interpreter Prototype Flyweight Iterator Builder Mediator Adapter Memento Bridge Observer Decorator State Strategy Template Method Visitor Pattern George Blankenship Visitor 2 The Elements of a Design Pattern • A pattern name • The problem that the pattern solves – Including conditions for the pattern to be applicable • The solution to the problem brought by the pattern – The elements (classes-objects) involved, their roles, responsibilities, relationships and collaborations – Not a particular concrete design or implementation • The consequences of applying the pattern – Time and space trade off – Language and implementation issues – Effects on flexibility, extensibility, portability Visitor Pattern George Blankenship 3 George Blankenship 1 Object-Oriented Desgin Visitor Pattern The Visitor Pattern: The Problem Represents an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates • many distinct and unrelated operations need to be performed on objects in an object structure an you want to avoid “polluting” their classes with these operations • the classes defining the object structure rarely change but you often want to define new operations over the structure Visitor Pattern George Blankenship 4 Visitor Example • The root of the structure accepts a visitor: root.accept( visitor ) • The root and every child object in the structure have a an accept method: void accept( visitor ) { visitor.visit( this ); for each child of mine child.accept( visitor ) next } • In short order our visitor gets a visit() call from each object in the collection.
    [Show full text]
  • Designpatternsphp Documentation Release 1.0
    DesignPatternsPHP Documentation Release 1.0 Dominik Liebler and contributors Jul 18, 2021 Contents 1 Patterns 3 1.1 Creational................................................3 1.1.1 Abstract Factory........................................3 1.1.2 Builder.............................................8 1.1.3 Factory Method......................................... 13 1.1.4 Pool............................................... 18 1.1.5 Prototype............................................ 21 1.1.6 Simple Factory......................................... 24 1.1.7 Singleton............................................ 26 1.1.8 Static Factory.......................................... 28 1.2 Structural................................................. 30 1.2.1 Adapter / Wrapper....................................... 31 1.2.2 Bridge.............................................. 35 1.2.3 Composite............................................ 39 1.2.4 Data Mapper.......................................... 42 1.2.5 Decorator............................................ 46 1.2.6 Dependency Injection...................................... 50 1.2.7 Facade.............................................. 53 1.2.8 Fluent Interface......................................... 56 1.2.9 Flyweight............................................ 59 1.2.10 Proxy.............................................. 62 1.2.11 Registry............................................. 66 1.3 Behavioral................................................ 69 1.3.1 Chain Of Responsibilities...................................
    [Show full text]
  • Behavioral Patterns
    Behavioral Patterns 101 What are Behavioral Patterns ! " Describe algorithms, assignment of responsibility, and interactions between objects (behavioral relationships) ! " Behavioral class patterns use inheritence to distribute behavior ! " Behavioral object patterns use composition ! " General example: ! " Model-view-controller in UI application ! " Iterating over a collection of objects ! " Comparable interface in Java !" 2003 - 2007 DevelopIntelligence List of Structural Patterns ! " Class scope pattern: ! " Interpreter ! " Template Method ! " Object scope patterns: ! " Chain of Responsibility ! " Command ! " Iterator ! " Mediator ! " Memento ! " Observer ! " State ! " Strategy ! " Visitor !" 2003 - 2007 DevelopIntelligence CoR Pattern Description ! " Intent: Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. ! " AKA: Handle/Body ! " Motivation: User Interfaces function as a result of user interactions, known as events. Events can be handled by a component, a container, or the operating system. In the end, the event handling should be decoupled from the component. ! " Applicability: ! " more than one object may handle a request, and the handler isn't known a priori. ! " Want to issue a request to one of several objects without specifying the receiver !" 2003 - 2007 DevelopIntelligence CoR Real World Example ! " The Chain of Responsibility pattern avoids coupling the sender of a request to the receiver, by giving more than one object a chance to handle the request. ! " Mechanical coin sorting banks use the Chain of Responsibility. Rather than having a separate slot for each coin denomination coupled with receptacle for the denomination, a single slot is used. When the coin is dropped, the coin is routed to the appropriate receptacle by the mechanical mechanisms within the bank.
    [Show full text]
  • Permissions, Visitor Pattern
    Selected Topics in Object Oriented Programming Lecture 3: More OOP principles Leonid Barenboim Permissions Permissions define the areas within a program from which a feature (field/ method) can be accessed: private – only within the same class. protected - only within the class and its subclasses. public – from everywhere. Permission in java Java use somewhat different rules: private – only within the same class. package – only within the same package. protected – within the same package and within the subclasses outside the package. public – from everywhere. Selecting the right permission The principle of encapsulation suggests the following rules: All non-static fields should be private Service methods should be public Helper methods should be private/protected Permission rules in specific languages Smalltalk – all fields are private all methods are public Scripting languages (e.g., python) - No permissions! - Everything is public! The Visitor Pattern Reminder: Polymorphism Reminder: Polymorphism Animal animal; animal = new Dog; Animal * animal.say(); \\ “Woof” animal = new Cat; + say() * animal.say(); \\ “Miau” Cat Dog + say() + say() System.out.println(“Miau”) System.out.println(“Woof”) What happens if a method accepts an argument? boolean b; Animal * Animal cat = new Cat(); Animal mouse = new + say() * Mouse(); + eats(mouse: Mouse) : bool * b = cat.eats(mouse); + eats(cat: Cat) : bool * //compilation error Cat Mouse + say() + say() +eats(mouse : Mouse) : bool +eats(mouse : Mouse) : bool +eats(cat : Cat) : bool +eats(cat : Cat) : bool No support for polymorphism of arguments • Java (and many other languages) supports only polymorphism of the receiver (the variable on which the method is invoked). • Polymorphism of the receiver is performed using single dispatch. • Polymorphism of arguments is performed using multiple-level dispatch, which is resource consuming.
    [Show full text]
  • Design Patterns in Ocaml
    Design Patterns in OCaml Antonio Vicente [email protected] Earl Wagner [email protected] Abstract The GOF Design Patterns book is an important piece of any professional programmer's library. These patterns are generally considered to be an indication of good design and development practices. By giving an implementation of these patterns in OCaml we expected to better understand the importance of OCaml's advanced language features and provide other developers with an implementation of these familiar concepts in order to reduce the effort required to learn this language. As in the case of Smalltalk and Scheme+GLOS, OCaml's higher order features allows for simple elegant implementation of some of the patterns while others were much harder due to the OCaml's restrictive type system. 1 Contents 1 Background and Motivation 3 2 Results and Evaluation 3 3 Lessons Learned and Conclusions 4 4 Creational Patterns 5 4.1 Abstract Factory . 5 4.2 Builder . 6 4.3 Factory Method . 6 4.4 Prototype . 7 4.5 Singleton . 8 5 Structural Patterns 8 5.1 Adapter . 8 5.2 Bridge . 8 5.3 Composite . 8 5.4 Decorator . 9 5.5 Facade . 10 5.6 Flyweight . 10 5.7 Proxy . 10 6 Behavior Patterns 11 6.1 Chain of Responsibility . 11 6.2 Command . 12 6.3 Interpreter . 13 6.4 Iterator . 13 6.5 Mediator . 13 6.6 Memento . 13 6.7 Observer . 13 6.8 State . 14 6.9 Strategy . 15 6.10 Template Method . 15 6.11 Visitor . 15 7 References 18 2 1 Background and Motivation Throughout this course we have seen many examples of methodologies and tools that can be used to reduce the burden of working in a software project.
    [Show full text]
  • Design Pattern Implementation in Java and Aspectj
    Design Pattern Implementation in Java and AspectJ Jan Hannemann Gregor Kiczales University of British Columbia University of British Columbia 201-2366 Main Mall 201-2366 Main Mall Vancouver B.C. V6T 1Z4 Vancouver B.C. V6T 1Z4 jan [at] cs.ubc.ca gregor [at] cs.ubc.ca ABSTRACT successor in the chain. The event handling mechanism crosscuts the Handlers. AspectJ implementations of the GoF design patterns show modularity improvements in 17 of 23 cases. These improvements When the GoF patterns were first identified, the sample are manifested in terms of better code locality, reusability, implementations were geared to the current state of the art in composability, and (un)pluggability. object-oriented languages. Other work [19, 22] has shown that implementation language affects pattern implementation, so it seems The degree of improvement in implementation modularity varies, natural to explore the effect of aspect-oriented programming with the greatest improvement coming when the pattern solution techniques [11] on the implementation of the GoF patterns. structure involves crosscutting of some form, including one object As an initial experiment we chose to develop and compare Java playing multiple roles, many objects playing one role, or an object [27] and AspectJ [25] implementations of the 23 GoF patterns. playing roles in multiple pattern instances. AspectJ is a seamless aspect-oriented extension to Java, which means that programming in AspectJ is effectively programming in Categories and Subject Descriptors Java plus aspects. D.2.11 [Software Engineering]: Software Architectures – By focusing on the GoF patterns, we are keeping the purpose, patterns, information hiding, and languages; D.3.3 intent, and applicability of 23 well-known patterns, and only allowing [Programming Languages]: Language Constructs and Features – the solution structure and solution implementation to change.
    [Show full text]
  • Java Design Patterns I
    Java Design Patterns i Java Design Patterns Java Design Patterns ii Contents 1 Introduction to Design Patterns 1 1.1 Introduction......................................................1 1.2 What are Design Patterns...............................................1 1.3 Why use them.....................................................2 1.4 How to select and use one...............................................2 1.5 Categorization of patterns...............................................3 1.5.1 Creational patterns..............................................3 1.5.2 Structural patterns..............................................3 1.5.3 Behavior patterns...............................................3 2 Adapter Design Pattern 5 2.1 Adapter Pattern....................................................5 2.2 An Adapter to rescue.................................................6 2.3 Solution to the problem................................................7 2.4 Class Adapter..................................................... 11 2.5 When to use Adapter Pattern............................................. 12 2.6 Download the Source Code.............................................. 12 3 Facade Design Pattern 13 3.1 Introduction...................................................... 13 3.2 What is the Facade Pattern.............................................. 13 3.3 Solution to the problem................................................ 14 3.4 Use of the Facade Pattern............................................... 16 3.5 Download the Source Code.............................................
    [Show full text]