Design Patterns for Developing Dynamically Adaptive

Total Page:16

File Type:pdf, Size:1020Kb

Design Patterns for Developing Dynamically Adaptive Design Patterns for Developing Dynamically Adaptive Systems ∗ Andres J. Ramirez and Betty H.C. Cheng Michigan State University 3115 Engineering Building East Lansing, Michigan 48824 {ramir105, chengb}@cse.msu.edu ABSTRACT 1. INTRODUCTION As applications grow in size and complexity, and computing As applications grow in size, complexity, and heterogene- infrastructure continues to evolve, it becomes increasingly ity in response to growing computational needs, it is increas- difficult to build a system that satisfies all requirements and ingly difficult to build a system that satisfies all require- constraints that might arise during its lifetime. As a result, ments and design constraints that it will encounter during there is an increasing need for software to adapt in response its lifetime. Many of these systems are required to run con- to new requirements and environmental conditions after it tinuously, disallowing long downtimes where humans look has been deployed. Due to their high complexity, adaptive for places to modify the code. As a result, it is important programs are generally difficult to specify, design, verify, and to be able to adapt an application’s behavior at run time in validate. In addition, the current lack of reusable design ex- response to changing requirements and environmental condi- pertise that can be leveraged from one adaptive system to tions [21]. IBM proposed autonomic computing [16] to meet another further exacerbates the problem. To address this this need, where a system manages itself based on high-level problem, we studied over thirty adaptation-related research objectives from a systems administrator, thus promoting and project implementations available from the literature self-management and self-reconfiguration. Due to their high and open sources to harvest adaptation-oriented design pat- complexity, adaptive and autonomic systems are generally terns that support the development of adaptive systems. difficult to specify, design, verify, and validate [32]. In addi- These patterns facilitate the separate development of the tion, the current lack of reusable design expertise that can be functional logic and the adaptive logic. We present these leveraged from one adaptive system to another further ex- design patterns within the context of a modeling-based de- acerbates the problem. To address this problem, we studied velopment process for dynamically adaptive systems. In or- over thirty adaptation-related research and project imple- der to address the assurance of these adaptive systems, the mentations available from the literature and open sources patterns also include templates for formally specifying in- to harvest and develop adaptation-oriented design patterns variant properties of adaptive systems. that support the development of adaptive systems. This pa- per describes the harvested adaptation design patterns and how they can be used to construct adaptive and autonomic Categories and Subject Descriptors systems. Most adaptive systems, including autonomic systems, com- D.2.11 [Software Architectures]: Design Patterns; D.2.10 prise three key elements: monitoring, decision-making, and [Design]: Methodologies reconfiguration. Monitoring enables an application to be aware of its environment and detect conditions warrant- ing reconfiguration; decision-making determines what set of Keywords monitored conditions should trigger a specific reconfigura- Design Patterns, Adaptive Systems, Autonomic Systems tion response; and reconfiguration enables an application to change itself in order to fulfill its requirements. Not only must developers design and implement each of these ele- ∗This work has been supported in part by NSF grants CCF- ments correctly, they must also carefully determine their 0541131, CNS-0551622, CCF-0750787, IIP-0700329, and CCF-0820220, Army Research Office W911NF-08-1-0495, interactions. For instance, if the monitoring process fails to and the Department of the Navy, Office of Naval Research report a significant environmental change, then the decision- under Grant No. N00014-01-1-0744, Ford Motor Company, making process may incorrectly trigger an unnecessary (or and a grant from Michigan State University’s Quality Fund. even detrimental) reconfiguration. Unfortunately, until re- cently, most approaches have addressed adaptation using ad hoc techniques [10]. To address these concerns, researchers Permission to make digital or hard copies of all or part of this work for have developed adaptation-enabling frameworks [2, 9], mid- personal or classroom use is granted without fee provided that copies are dleware [18, 23], and language-based support [28]. These not made or distributed for profit or commercial advantage and that copies approaches, however, tend to be tightly coupled with spe- bear this notice and the full citation on the first page. To copy otherwise, to republish, to post on servers or to redistribute to lists, requires prior specific cific domains or technologies, thus limiting their applicabil- permission and/or a fee. ity with respect to the problem being addressed. Design ICAC ’09 Barcelona, Spain patterns, on the other hand, work at the modeling and de- Copyright 200X ACM X-XXXXX-XX-X/XX/XX ...$5.00. sign level of abstraction, thereby potentially increasing the pares our pattern-based approach with a framework-based amount of design reuse when compared to other approaches. approach. Lastly, Section 7 presents our main findings and This paper presents twelve adaptation-oriented design pat- discusses future directions of work. terns to facilitate the reuse of adaptation expertise. In the spirit of the original design patterns by Gamma et al. [8], 2. BACKGROUND each of the adaptation-oriented design patterns were devel- oped by generalizing several existing design solutions. For This section briefly introduces two key topics fundamental each design pattern, we use platform-independent models to this paper, design patterns and the model-based develop- to represent the solution. In addition, by focusing on the ment process by Zhang and Cheng [32]. recurring challenges found in monitoring, decision-making, and reconfiguration activities, our design patterns separate 2.1 Design Patterns the adaptive logic from the functional logic. This separation A design pattern is a general and reusable solution to a of concerns facilitates the reuse of adaptation designs across commonly recurring problem in design [8]. A software de- multiple applications and domains. Similarly, while harvest- sign pattern does not provide code, nor can it be directly ing each candidate design, we have observed recurring inter- transformed into code. Instead, a design pattern identifies actions between monitoring, decision-making, and reconfig- and abstractly models the key aspects of a common design uration processes. This information enables us to suggest structure that make it useful for creating a reusable object- which design patterns should be used together. Lastly, we oriented design. Each design pattern has four essential ele- extended the design pattern template introduced by Gamma ments [8]. A pattern name is a handle that can be used to et al. [8] with a Behavior and Constraints fields. Constraints describe a design pattern, its solutions, and consequences. contain specific templates that can be used to specify invari- The problem describes under what context to apply the de- ant properties that must be satisfied by state-based models sign pattern. The solution describes the elements that make from the Behavior field once the design pattern is instanti- up the design, their relationships, responsibilities, and col- ated. Since our approach is compatible with the high assur- laborations. Lastly, the consequences describe the results ance model-based development process for adaptive systems and tradeoffs of applying the design pattern. Each of these previously introduced by Zhang and Cheng [32], automated four essential elements are organized and presented in the verification techniques can be used to analyze the instan- design pattern template fields. tiated design patterns against functional and adaptation- specific properties. 2.2 Model-based Development Process Harvesting design patterns is a difficult and subjective Zhang and Cheng [32] previously introduced a model- task for two main reasons. First, it is impractical to ex- based development process with the objective of guiding the amine all available systems and research projects associated rigorous development of adaptive programs. The process with adaptation. Second, some of the surveyed systems had separates the adaptive behavior and the non-adaptive be- little to no documentation accompanying their design. To havior specifications of adaptive programs. By doing so, the ensure that the design patterns harvested were sufficiently respective models are easier to specify and more amenable to mature to aid developers in building adaptive systems, we automated analysis, visual inspection, and modification. As performed two forms of validation in this work. First, we Figure 1 illustrates, the process starts with high-level system found additional instances of our design patterns in other goals (G) and progresses through design models (Mi, Mj ) adaptive systems. In some cases, information from these to code. The focus of the process is the specification of key new instances enabled us to further generalize the solutions properties (e.g., Φi, Φj ) at each of the major development and refine the design patterns. Second, we re-engineered phases. While the original work used Petri-nets
Recommended publications
  • APPLYING MODEL-VIEW-CONTROLLER (MVC) in DESIGN and DEVELOPMENT of INFORMATION SYSTEMS an Example of Smart Assistive Script Breakdown in an E-Business Application
    APPLYING MODEL-VIEW-CONTROLLER (MVC) IN DESIGN AND DEVELOPMENT OF INFORMATION SYSTEMS An Example of Smart Assistive Script Breakdown in an e-Business Application Andreas Holzinger, Karl Heinz Struggl Institute of Information Systems and Computer Media (IICM), TU Graz, Graz, Austria Matjaž Debevc Faculty of Electrical Engineering and Computer Science, University of Maribor, Maribor, Slovenia Keywords: Information Systems, Software Design Patterns, Model-view-controller (MVC), Script Breakdown, Film Production. Abstract: Information systems are supporting professionals in all areas of e-Business. In this paper we concentrate on our experiences in the design and development of information systems for the use in film production processes. Professionals working in this area are neither computer experts, nor interested in spending much time for information systems. Consequently, to provide a useful, useable and enjoyable application the system must be extremely suited to the requirements and demands of those professionals. One of the most important tasks at the beginning of a film production is to break down the movie script into its elements and aspects, and create a solid estimate of production costs based on the resulting breakdown data. Several film production software applications provide interfaces to support this task. However, most attempts suffer from numerous usability deficiencies. As a result, many film producers still use script printouts and textmarkers to highlight script elements, and transfer the data manually into their film management software. This paper presents a novel approach for unobtrusive and efficient script breakdown using a new way of breaking down text into its relevant elements. We demonstrate how the implementation of this interface benefits from employing the Model-View-Controller (MVC) as underlying software design paradigm in terms of both software development confidence and user satisfaction.
    [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]
  • A Design Pattern Generation Tool
    Project Number: GFP 0801 A DESIGN PATTERN GEN ERATION TOOL A MAJOR QUALIFYING P ROJECT REPORT SUBMITTED TO THE FAC ULTY OF WORCESTER POLYTECHNIC INSTITUTE IN PARTIAL FULFILLME NT OF THE REQUIREMEN TS FOR THE DEGREE OF BACHELOR O F SCIENCE BY CAITLIN VANDYKE APRIL 23, 2009 APPROVED: PROFESSOR GARY POLLICE, ADVISOR 1 ABSTRACT This project determines the feasibility of a tool that, given code, can convert it into equivalent code (e.g. code that performs the same task) in the form of a specified design pattern. The goal is to produce an Eclipse plugin that performs this task with minimal input, such as special tags.. The final edition of this plugin will be released to the Eclipse community. ACKNOWLEGEMENTS This project was completed by Caitlin Vandyke with gratitude to Gary Pollice for his advice and assistance, as well as reference materials and troubleshooting. 2 TABLE OF CONTENTS Abstract ....................................................................................................................................................................................... 2 Acknowlegements ................................................................................................................................................................... 2 Table of Contents ..................................................................................................................................................................... 3 Table of Illustrations .............................................................................................................................................................
    [Show full text]
  • Design Patterns
    CSE 403: Software Engineering, Winter 2016 courses.cs.washington.edu/courses/cse403/16wi/ Design Patterns Emina Torlak [email protected] Outline • Overview of design patterns • Creational patterns • Structural patterns • Behavioral patterns 2 introoverview of design patterns What is a design pattern? 4 What is a design pattern? • A standard solution to a common programming problem • a design or implementation structure that achieves a particular purpose • a high-level programming idiom 4 What is a design pattern? • A standard solution to a common programming problem • a design or implementation structure that achieves a particular purpose • a high-level programming idiom • A technique for making code more flexible or efficient • reduce coupling among program components • reduce memory overhead 4 What is a design pattern? • A standard solution to a common programming problem • a design or implementation structure that achieves a particular purpose • a high-level programming idiom • A technique for making code more flexible or efficient • reduce coupling among program components • reduce memory overhead • Shorthand for describing program design • a description of connections among program components • the shape of a heap snapshot or object model 4 Why should you care? • You could come up with these solutions on your own … • But you shouldn't have to! • A design pattern is a known solution to a known problem. 5 Types of design patterns • Creational patterns • how objects are instantiated • Structural patterns • how objects / classes can
    [Show full text]
  • Object-Oriented Design Patterns
    Object-Oriented Design Patterns David Janzen EECS 816 Object-Oriented Software Development University of Kansas Outline • Introduction – Design Patterns Overview – Strategy as an Early Example – Motivation for Creating and Using Design Patterns – History of Design Patterns • Gang of Four (GoF) Patterns – Creational Patterns – Structural Patterns – Behavioral Patterns Copyright © 2006 by David S. 2 Janzen. All rights reserved. What are Design Patterns? • In its simplest form, a pattern is a solution to a recurring problem in a given context • Patterns are not created, but discovered or identified • Some patterns will be familiar? – If you’ve been designing and programming for long, you’ve probably seen some of the patterns we will discuss – If you use Java Foundation Classes (Swing), Copyright © 2006 by David S. 3 you have certaJiannzleyn. Aulls rieghdts rsesoervmed.e design patterns Design Patterns Definition1 • Each pattern is a three-part rule, which expresses a relation between – a certain context, – a certain system of forces which occurs repeatedly in that context, and – a certain software configuration which allows these forces to resolve themselves 1. Dick Gabriel, http://hillside.net/patterns/definition.html Copyright © 2006 by David S. 4 Janzen. All rights reserved. A Good Pattern1 • Solves a problem: – Patterns capture solutions, not just abstract principles or strategies. • Is a proven concept: – Patterns capture solutions with a track record, not theories or speculation 1. James O. Coplien, http://hillside.net/patterns/definition.html Copyright © 2006 by David S. 5 Janzen. All rights reserved. A Good Pattern • The solution isn't obvious: – Many problem-solving techniques (such as software design paradigms or methods) try to derive solutions from first principles.
    [Show full text]
  • Masquerading and Adaptation Design Patterns in Python (Pdf)
    Click to Edit Title Masquerading and Adaptation Click to Edit DesignPresenter P atInformationterns in Python O’Reilly Open Source Convention July 26–30, 2004 Alex Martelli <[email protected]> July 26–30, 2004 Portland, OR STRAKT © 2004 AB Strakt 1 This talk's audience...: "fair" to "excellent" grasp of Python and OO development "none" to "good" grasp of Design Patterns in general want to learn more about: DPs, masquerading, adaptation, DPs for Python, DP/language issues © 2004 AB Strakt 2 STRAKT What we'll cover...: Design Patterns, including "myths and realities" the Holder and Wrapper Python idioms the Adapter DP the Facade DP the Currying DP and Python callback systems the Decorator DP the Protocol Adaptation proposal (PEP 246) ...and, iff time allows...: • the Proxy DP • the Bridge DP © 2004 AB Strakt 3 STRAKT Next up...: Design Patterns, myths and realities Holder and Wrapper Adapter Facade Currying Decorator Protocol Adaptation (PEP 246) Proxy Bridge © 2004 AB Strakt 4 STRAKT Design Patterns rich, thriving subculture of the OO development culture Gamma, Helms, Johnson, Vlissides, "Design Patterns", Addison-Wesley more introductory: Shalloway, Trott, "Design Patterns Explained" (AW) PLoP conferences & books © 2004 AB Strakt 5 STRAKT ...but also... Design Patterns risked becoming a "fad" or "fashion" recently • cause: the usual, futile search for Image has been scaled down. See full-size image. Remove Frame the "silver bullet"...! Back to Results www.avshop.com/productimages/ products/4514-300.jp • 277 x 300 pixels - 8k This image may be subject to copyright. let's not throwBelow the is the imagedesign in its origi nalpat contextterns on the page: www.avshop.com/ catalog/product.html?productid=451 out with the silver bullet! beam allows you to see clearly in the Catalog Quick Order darkest places.
    [Show full text]
  • Design Patterns and Software Engineering Techniques for Java, and How They May Apply to Chisel
    HOW IT IS DONE IN JAVA Design Patterns and Software Engineering Techniques for Java, and how they may apply to Chisel CS 294-88: Declarative Hardware Design Martin Maas, 03/05/2013 Introduction I Java has been very popular language in production use for a long time (especially enterprise applications). I Significant performance overheads (GC, JIT,...), yet people are using it for big, mission-critical applications. I Reason (arguably): Enforces rigorous design methodology; availability of a large set of design patterns and tools. I Many of these should be applicable to Chisel (Scala is fundamentally similar to Java, concepts may carry over). I Much of this will be familiar to you already - this talk is intended to organize the content and create a basis for discussion of how to use these techniques in Chisel. Talk Organization 1. Design Strategies 2. Dependency Injection 3. Testing & Mocking 4. Java Tools Part I: Design Strategies Strategy 1: Use Interfaces whenever feasibly possible I Na¨ıveStrategy: When using a component, refer to it by its class type and create an instance of that class. Foo foo = new Foo(); I Problem #1: What if we suddenly need to use a different implementation (e.g. for testing)? I Aside: Could use inheritance, but this breaks abstraction - ideally, declare all classes that are not specifically designed to be inherited from as final. I Problem #2: What if we have a class that wants to provide multiple functionalities? I For example: Consider some class SignalToImageDSP representing a pipeline stage that takes signal data and produces image data. Strategy 1: Use Interfaces whenever feasibly possible I Use when initializing a pipeline: SignalDSP prevStage= new SignalDSP(); SignalToImageDSP stage= new SignalToImageDSP(prevStage); ImageDSP nextStage= new ImageProc(stage); I Say we decide at some point that we want to use a truncated version of the pipeline, where the image data is approximated without using sensors.
    [Show full text]
  • A Comparison of Parallel Design Patterns for Game Development
    Faculty of TeknikTechnol ochogy & samh Soci¨alleety ComDatavetenskapputer Science och medieteknik Graduate Thesis 15Examensarbete hp, elementary 15 h¨ogskolepo¨ang, grundniv˚a A Comparison of Parallel Design Patterns for GameExamensarbetets Development titel En Jämförelse av Parallella Designmönster för Spelutveckling Examensarbetets titel p˚aengelska (p˚asvenska om arbetet ¨ar skrivet p˚aengelska) Robin Andblom F¨orfattaresCarl Sjöberg namn var och en p˚aegen rad, i bokstavsordning efter efternamn Thesis: Bachelor 180 hp Main �ield: Computer Science Program: Game Development Supervisor: Carl Johan Gribel Date of �inal seminar: 2018-01-15 Examiner: Carl-Magnus Olsson Eventuell bild Examen: kandidatexamen 180 hp Handledare: XYZ Huvudomr˚ade: datavetenskap Examinator: ABC Program: (t.ex. systemutvecklare) Datum f¨or slutseminarium: (t.ex. 2018-05-30) AComparisonofParallelDesignPatternsforGame Development Robin Andblom, Carl Sj¨oberg Malm¨o, Sweden Abstract As processor performance capabilities can only be increased through the use of a multicore architecture, software needs to be developed to utilize the par- allelism o↵ered by the additional cores. Especially game developers need to seize this opportunity to save cycles and decrease the general rendering time. One of the existing advances towards this potential has been the creation of multithreaded game engines that take advantage of the additional processing units. In such engines, di↵erent branches of the game loop are parallelized. However, the specifics of the parallel design patterns used are not outlined. Neither are any ideas of how to combine these patterns proposed. These missing factors are addressed in this article, to provide a guideline for when to use which one of two parallel design patterns; fork-join and pipeline par- allelism.
    [Show full text]
  • Chapter 3 – Design Patterns: Model-View- Controller
    SOFTWARE ARCHITECTURES Chapter 3 – Design Patterns: Model-View- Controller Martin Mugisha Brief History Smalltalk programmers developed the concept of Model-View-Controllers, like most other software engineering concepts. These programmers were gathered at the Learning Research Group (LRG) of Xerox PARC based in Palo Alto, California. This group included Alan Kay, Dan Ingalls and Red Kaehler among others. C language which was developed at Bell Labs was already out there and thus they were a few design standards in place[ 1] . The arrival of Smalltalk would however change all these standards and set the future tone for programming. This language is where the concept of Model-View- Controller first emerged. However, Ted Kaehler is the one most credited for this design pattern. He had a paper in 1978 titled ‘A note on DynaBook requirements’. The first name however for it was not MVC but ‘Thing-Model-View-Set’. The aim of the MVC pattern was to mediate the way the user could interact with the software[ 1] . This pattern has been greatly accredited with the later development of modern Graphical User Interfaces(GUI). Without Kaehler, and his MVC, we would have still been using terminal to input our commands. Introduction Model-View-Controller is an architectural pattern that is used for implementing user interfaces. Software is divided into three inter connected parts. These are the Model, View, and Controller. These inter connection is aimed to separate internal representation of information from the way it is presented to accepted users[ 2] . fig 1 SOFTWARE ARCHITECTURES As shown in fig 1, the MVC has three components that interact to show us our unique information.
    [Show full text]
  • 240, 8).Sodium(1).Build();
    23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour of the Gang-of-Four Design Patterns Josh Bloch Charlie Garrod School of Computer Science 15-214 1 Administrivia • Homework 6 checkpoint due Friday 5 pm • Final exam Tuesday, May 3, 5:30-8:30 pm, PH 100 • Final review session Sunday, May, 7-9 pm, DH 1112 15-214 2 Key concept from Tuesday… MapReduce with key/value pairs (Google style) • Master – Assign tasks to workers – Ping workers to test for failures • Map workers the shuffle: – Map for each key/value pair – Emit intermediate key/value pairs 15-214 3 Key concept from Tuesday… MapReduce with key/value pairs (Google style) • E.g., for each word on the Web, count the number of times that word occurs § For Map: key1 is a document name, value is the contents of that document § For Reduce: key2 is a word, values is a list of the number of counts of that word f1(String key1, String value): f2(String key2, Iterator values): for each word w in value: int result = 0; EmitIntermediate(w, 1); for each v in values: result += v; Emit(key2, result); Map: (key1, v1) à (key2, v2)* Reduce: (key2, v2*) à (key3, v3)* MapReduce: (key1, v1)* à (key3, v3)* MapReduce: (docName, docText)* à (word, wordCount)* 15-214 4 Outline I. Creational Patterns II. Structural Patterns III. Behavioral Patterns 15-214 5 Pattern Name • Intent – the aim of this pattern • Use case – a motivating example • Key types – the interfaces that define pattern • JDK – example(s) of this pattern in the JDK 15-214 6 Illustration • Code sample, diagram, or drawing – Time constraints make it impossible to include illustrations from some patterns • Some patterns lack an illustration L 15-214 7 I.
    [Show full text]
  • Automated Refactoring to the Null Object Design Pattern
    Automated Refactoring to the Null Object Design Pattern Maria Anna G. Gaitania, Vassilis E. Zafeirisa, N. A. Diamantidisa, E. A. Giakoumakisa,∗ aDepartment of Informatics, Athens University of Economics and Business, 76 Patission Str., Athens 104 34, Greece Abstract Context: Null-checking conditionals are a straightforward solution against null dereferences. However, their frequent repetition is considered a sign of poor program design, since they introduce source code duplication and complexity that impacts code comprehension and maintenance. The Null Object design pattern enables the replacement of null-checking conditionals with polymorphic method invocations that are bound, at runtime, to either a real object or a Null Object. Objective: This work proposes a novel method for automated refactoring to Null Object that eliminates null-checking conditionals associated with optional class fields, i.e., fields that are not initialized in all class instan- tiations and, thus, their usage needs to be guarded in order to avoid null dereferences. Method: We introduce an algorithm for automated discovery of refacto- ring opportunities to Null Object. Moreover, we specify the source code transformation procedure and an extensive set of refactoring preconditions for safely refactoring an optional field and its associated null-checking con- ditionals to the Null Object design pattern. The method is implemented as an Eclipse plug-in and is evaluated on a set of open source Java projects. Results: Several refactoring candidates are discovered in the projects used ∗Corresponding author. Address: Patission 76, 104 34, Athens, Greece. Tel: +302108203183, Fax: +302108203275 Email addresses: [email protected] (Maria Anna G. Gaitani), [email protected] (Vassilis E.
    [Show full text]
  • The Strategy Pattern Intent Motivation
    The Strategy Pattern G Intent ³ Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. G Motivation The State and Strategy Patterns Design Patterns In Java Bob Tarr 37 The Strategy Pattern G Applicability Use the Strategy pattern whenever: ¨ Many related classes differ only in their behavior ¨ You need different variants of an algorithm ¨ An algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures. ¨ A class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class. The State and Strategy Patterns Design Patterns In Java Bob Tarr 38 The Strategy Pattern G Structure The State and Strategy Patterns Design Patterns In Java Bob Tarr 39 The Strategy Pattern G Consequences ³ Benefits ¨ Provides an alternative to subclassing the Context class to get a variety of algorithms or behaviors ¨ Eliminates large conditional statements ¨ Provides a choice of implementations for the same behavior ³ Liabilities ¨ Increases the number of objects ¨ All algorithms must use the same Strategy interface The State and Strategy Patterns Design Patterns In Java Bob Tarr 40 Strategy Pattern Example 1 G Situation: A class wants to decide at run-time what algorithm it should use to sort an array. Many different sort algorithms are already available. G Solution: Encapsulate the different sort algorithms using the Strategy pattern! SortArray SortStrategy sortStrategy sort( ) sort( ) BubbleSort QuickSort InsertionSort sort( ) sort( ) sort( ) The State and Strategy Patterns Design Patterns In Java Bob Tarr 41 Strategy Pattern Example 2 G Situation: A GUI container object wants to decide at run-time what strategy it should use to layout the GUI components it contains.
    [Show full text]