How To Use The Command Pattern In Java.Com (Programming) To Create A Program That Is Atomic And Is Not A Command Pattern (Programmer)



Similar documents
Computing Concepts with Java Essentials

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Java the UML Way: Integrating Object-Oriented Design and Programming

Java (12 Weeks) Introduction to Java Programming Language

Java Application Developer Certificate Program Competencies

Patterns in. Lecture 2 GoF Design Patterns Creational. Sharif University of Technology. Department of Computer Engineering

How To Design Software

Designing and Writing a Program DESIGNING, CODING, AND DOCUMENTING. The Design-Code-Debug Cycle. Divide and Conquer! Documentation is Code

Fundamentals of Java Programming

CMSC 132: Object-Oriented Programming II. Design Patterns I. Department of Computer Science University of Maryland, College Park

Assignment # 2: Design Patterns and GUIs

Moving from CS 61A Scheme to CS 61B Java

PL/SQL Programming Workbook

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Principles of Software Construction: Objects, Design and Concurrency. GUIs with Swing. toad Spring 2013

1. What are Data Structures? Introduction to Data Structures. 2. What will we Study? CITS2200 Data Structures and Algorithms

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

Chapter 1 Fundamentals of Java Programming

History OOP languages Year Language 1967 Simula Smalltalk

Glossary of Object Oriented Terms

GUI Event-Driven Programming

Contents. Introduction and System Engineering 1. Introduction 2. Software Process and Methodology 16. System Engineering 53

1 File Processing Systems

How Scala Improved Our Java

Project 4 DB A Simple database program

JiST Graphical User Interface Event Viewer. Mark Fong

Oracle Database Security and Audit

The ConTract Model. Helmut Wächter, Andreas Reuter. November 9, 1999

The Command Pattern. The Command Pattern: Motivation

Developing GUI Applications: Architectural Patterns Revisited

Android Application Development Course Program

How To Understand The Dependency Inversion Principle (Dip)

Design with Reuse. Building software from reusable components. Ian Sommerville 2000 Software Engineering, 6th edition. Chapter 14 Slide 1

Design Patterns. V Software Engineering Lecture 8. Adapted from Prof. Necula CS 169, Berkeley 1

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

Tutorial on Writing Modular Programs in Scala

MiniDraw Introducing a framework... and a few patterns

æ A collection of interrelated and persistent data èusually referred to as the database èdbèè.

Habanero Extreme Scale Software Research Project

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

Transactions and Recovery. Database Systems Lecture 15 Natasha Alechina

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

Chapter 6: Programming Languages

Recovery System C H A P T E R16. Practice Exercises

Structural Design Patterns Used in Data Structures Implementation

Design Patterns for Games

Syllabus for CS 134 Java Programming

Implementação. Interfaces Pessoa Máquina 2010/ Salvador Abreu baseado em material Alan Dix. Thursday, June 2, 2011

DEVELOPMENT OF AN ANALYSIS AND REPORTING TOOL FOR ORACLE FORMS SOURCE CODES

Basic SQL Server operations

Computer Science III Advanced Placement G/T [AP Computer Science A] Syllabus

Iterator Pattern. CSIE Department, NTUT Chien-Hung Liu. Provide a way to access the elements of an aggregate object sequentially

Tutorial Reference Manual. Java WireFusion 4.1

Introduction to Database Management Systems

KASPERSKY LAB. Kaspersky Administration Kit version 6.0. Administrator s manual

Lesson Plans Microsoft s Managing and Maintaining a Microsoft Windows Server 2003 Environment

The Basic Java Applet and JApplet

Génie Logiciel et Gestion de Projets. Patterns

El Dorado Union High School District Educational Services

JOURNAL OF OBJECT TECHNOLOGY

Getting Started with the Internet Communications Engine

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Programming and Software Development CTAG Alignments

Object oriented design process

Tivoli Storage Manager Explained

ATM Case Study OBJECTIVES Pearson Education, Inc. All rights reserved Pearson Education, Inc. All rights reserved.

VMware Mirage Web Manager Guide

C# Cookbook. Stephen Teilhet andjay Hilyard. O'REILLY 8 Beijing Cambridge Farnham Köln Paris Sebastopol Taipei Tokyo '"J""'

Table of Contents. Adding Build Targets to the SDK 8 The Android Developer Tools (ADT) Plug-in for Eclipse 9

3] Alert Configuration for User Login Failure and Incorrect Guest Details [HIA]

The Rules 1. One level of indentation per method 2. Don t use the ELSE keyword 3. Wrap all primitives and Strings

Chapter 10. Backup and Recovery

CS 111 Classes I 1. Software Organization View to this point:

Software Design Principles and Guidelines

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

The Command Dispatcher Pattern

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

COMPUTER SCIENCE. 1. Computer Fundamentals and Applications

Centralized Disaster Recovery using RDS

Java EE Web Development Course Program

System types. Distributed systems

Web Application Development for the SOA Age Thinking in XML

Exercise 8: SRS - Student Registration System

Object Oriented Design

C++ INTERVIEW QUESTIONS

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

mframe Software Development Platform KEY FEATURES

Administering the Web Server (IIS) Role of Windows Server

Automated Data Collection for Usability Evaluation in Early Stages of Application Development

Unit 12 Database Recovery

Transcription:

CS 342: Object-Oriented Software Development Lab Command Pattern and Combinations David L. Levine Christopher D. Gill Department of Computer Science Washington University, St. Louis levine,cdgill@cs.wustl.edu http://classes.cec.wustl.edu/çcs342/ The Observer Pattern Intent Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Subject notifies registered observers of state changes Dependents (observers) can query subject state This pattern resolves the following forces: 1. An observer has state that should mirror that of its subject, though not continuously 2. Observers must be decoupled from subject A subject can have any number of observers An observer can monitor multipe subjects 3. Allows any number of observers Copyright c1997-2000 Dept. of Computer Science, Washington University 1 Structure of the Observer Pattern Example of the Observer Pattern Subject attach/register detach notify for each observer { update_sort ConcreteSubject subject_state Observer update_ Main_Observer update observer_state Sorter register_observer publish_update for each observer { update_sort 1. Selection_Sort notifies Sorter of state update Selection_Sort start_sort Sort_Request 2. Sorter iterates over Sort_Observers, and Sort_Observer update_sort 3. notifies each observer Main_Observer update_sort Sort_Request 4. each concrete observer performs its update action Copyright c1997-2000 Dept. of Computer Science, Washington University 2 Copyright c1997-2000 Dept. of Computer Science, Washington University 3

Observer Abstract Interface class Sort_Observer { public: // Manager functions. Sort_Observer () { virtual Sort_Observer (); Subject Abstract Interface // Implementor functions, for use by Sorter clients. int register_observer (Sort_Observer &sort_observer); // Register an observer for the sort. Returns 0 on succe // -1 on failure (reached maximum number of observers). static unsigned int maximum_observers (); // Implementor functions. virtual void update_sort (const Sort_Response &sort_obser // Callback, to receive a sort observation. ; protected: // Manager functions, for use by Sort algorithms. Sorter (); // Implementor functions, for use by Sort algorithms. void publish_sort_update (const Sort_Response &sort_obser // Used by Sort algorithms to publish updates on Sort sta // to registered observers. Copyright c1997-2000 Dept. of Computer Science, Washington University 4 Copyright c1997-2000 Dept. of Computer Science, Washington University 5 Observer Benefits The Memento Pattern Decouples observer from subject Allows an observer to monitor multiple subjects Allows any number of observers Intent Capture and externalize an object s internal state, without violating encapsulation, so that the object state can be restored later. Hides state storage implementation details from the object. Useful for persistent storage and transaction rollback operations. This pattern resolves the following forces: 1. Hide (and therefore allows transparent change of) state storage implementation details. 2. Externalize an objects internal state without breaking encapsulation. Copyright c1997-2000 Dept. of Computer Science, Washington University 6 Copyright c1997-2000 Dept. of Computer Science, Washington University 7

Structure of the Memento Pattern Originator creatememento () setmemento (Memento &m) state state = m.getstate (); return new Memento (state) Memento setstate () getstate () state Caretaker Use of the Memento Pattern // IterationState is the Memento for our Iterator. template <class T, class IterationState> class Iterator public: virtual IterationState * first () = 0; // Resets the iterator to the beginning. virtual int next (IterationState *) = 0; // Advance the iterator to the next item. virtual int is_done (const IterationState *) const = 0; // Returns 1 if we ve seen all the items, else 0. virtual int current_item (const IterationState *, T &item) const = 0; // Accesses the current item. Copyright c1997-2000 Dept. of Computer Science, Washington University 8 Copyright c1997-2000 Dept. of Computer Science, Washington University 9 Advantages of Memento-based Iterator Derived (concrete) Iterators need not store any state. The iteration state is stored in the IterationState class. An Iterator does not need to be a friend of its collection. Collection-specific private details are confined the Memento (IterationState class). Readily enables support for multiple iterators on one collection. Case Study with the Command Pattern Example Use of Command Pattern: Database Operations and Transactions Command Pattern Example Use of Command Pattern: Java MenuItem Template Method Pattern, to encapsulate atomicity Composite Pattern, to combine Commands into macros Copyright c1997-2000 Dept. of Computer Science, Washington University 10 Copyright c1997-2000 Dept. of Computer Science, Washington University 11

Database Operations and Transactions Database Operations are Commands Database operations query or update the state of the database. Database systems support transactions, atomic groups of operations. Transactions can be arbitrarily complex, but are constructed using simpler building blocks, i.e., database operations such as account debit and credits. Operations are verbs, but it would be nice to treat them as nouns (objects). To support logging for audits, crash recovery, rollbacks, etc.. To support queuing for batch or remote processing To support undo of completed operations To support security via encryption Database operations are query or update requests on the database. The Command Pattern encapsulates operations as objects. Each database operation and transaction manages its own undo operation. Allows composition of operations to create (atomic) transactions. Copyright c1997-2000 Dept. of Computer Science, Washington University 12 Copyright c1997-2000 Dept. of Computer Science, Washington University 13 Database Transactions are Commands Database transactions can be complex, and composed of operations or other transactions. Database transactions must be atomic, e.g., Consider moving funds from a savings account to a checking account, implemented by a debit from the savings account and a credit to the checking account. If either the debit or credit fail, then the entire transaction must fail. If the transaction fails but part of it had succeeded, then the successful part must be undone (rolled back). The Command Pattern Intent Encapsulate an operation as an object. parameterize clients with different operations buffer or log operations support reversal (undo) of operations also known as Action and Transaction Resolves the following forces: Decouple the object invoking an operation from the object that performs it. Bind an operation to the Receiver (of any class!) that performs it. Treat commands as first-class objects, so that they can be extended, encapsulated, combined, etc.. Make it easy to change or add new operations. Copyright c1997-2000 Dept. of Computer Science, Washington University 14 Copyright c1997-2000 Dept. of Computer Science, Washington University 15

Other Example Uses of Command Pattern Toolkit objects provide a mechanism for invoking an operation, but the toolkit has no knowledge of the operation. Window buttons and menus: the toolkit provides the mechanism for activating an operation, but the application must supply the actual operation. Encryption/decryption, where part of the decryption algorithm is passed along with the encrypted text. Contrast with Strategy pattern, where the algorithm must be known in advance. Downloadable code, e.g., with Java. The code is the operation(s), but it is encapsulated as an object. Structure of the Command Pattern Application Receiver Invoker 1. Application creates the Command and associates it with a Receiver action () receiver_->action () 3. Receiver performs operation 2. Invoker requests operation Command execute () 1a. implements Concrete Command execute () state receiver_ Copyright c1997-2000 Dept. of Computer Science, Washington University 16 Copyright c1997-2000 Dept. of Computer Science, Washington University 17 Java MenuItem Command Pattern Example Sort_Viewer 1. Application creates the Command and associates it with a Receiver Java System exit () 3. Receiver performs operation quit MenuItem actionperformed () 2. Invoker requests operation System.exit (0) Action Listener 1a. implements anon Action Listener actionperformed () added ActionListener Java MenuItem Participants Our Sort_Viewer has a Quit MenuItem: Menu menu = new Menu ("Sort_Viewer"); // "Quit" is the Command. MenuItem quit = new MenuItem ("Quit"); The Application associates each MenuItem with an ActionListener: public interface ActionListener extends EventListener { /** * Invoked when an action occurs. */ public void actionperformed(actionevent e); Copyright c1997-2000 Dept. of Computer Science, Washington University 18 Copyright c1997-2000 Dept. of Computer Science, Washington University 19

Java MenuItem Participants, (cont d) For the Quit Command, we create an ActionListener whose actionperformed terminates the program. The Receiver is Java s System class. The Receiver s action is its static exit method. new ActionListener () { public void actionperformed (ActionEvent e) { System.exit (0); Our concrete ActionListener is of an anonymous (unnamed) type. Java MenuItem Participants, (cont d) The anonymous ActionListener is the Concrete Command. Its addactionlistener binds it to its Receiver. Its actionperformed method calls its Receiver s operation, i.e., exit (). quit.addactionlistener ( new ActionListener () { public void actionperformed (ActionEvent e) { System.exit (0); ); The Quit MenuItem Invoker calls the the abstract ActionListener s actionperformed method. Copyright c1997-2000 Dept. of Computer Science, Washington University 20 Copyright c1997-2000 Dept. of Computer Science, Washington University 21 Limitations of Command Pattern Must create one Concrete Command class per type of command. Usually acceptable for MenuItems, because screen real estate limits those to a manageable number. But for, e.g., database operations, there could be many more types of commands. Consider adding atomicity to database operations. Database systems already provide atomicity through transactions. Could provide an atomic version of each database operation by subclassing a transaction version of it, e.g., Atomic_Debit_Operation () { begin_transaction (); perform_debit_operation (); end_transaction (); Limitations of Command Pattern However, that doubles the number of Concrete Command classes. And, each Atomic_Operation looks similar: begin/operation/end. If that similar code needed update, e.g., to add exception handling support, the update would be required for each of the derived Atomic classes. Enter the Template Method pattern. Copyright c1997-2000 Dept. of Computer Science, Washington University 22 Copyright c1997-2000 Dept. of Computer Science, Washington University 23

The Template Method Pattern Intent Define an algorithm skeleton in an operation, but defer some steps to subclasses. Subclasses redefine those steps. The algorithm structure (ordering of steps) are usually fixed. Resolves the following forces: Algorithm structure and commonality should be factored out. Only certain steps of the algorithm need to be customized. Very useful for avoiding code duplication, of the invariant steps of the algorithm. Contrast with Strategy pattern, which uses delegation instead of inheritance. With Template Method, the algorithm steps must be defined at compile time. Structure of the Template Method Pattern AbstractClass TemplateMethod () operation1 () operation2 () ConcreteClass operation1 () operation2 () implements operation1 () operation2 () Copyright c1997-2000 Dept. of Computer Science, Washington University 24 Copyright c1997-2000 Dept. of Computer Science, Washington University 25 Combining Command and Template Method Patterns Instead of creating a separate version of each database operation that s atomic, use a Template Method, e.g., Atomic_Operation () { begin_transaction (); perform_operation (); end_transaction (); Subclasses of abstract Atomic_Operation fill in their own perform_operation () implementation. Combining Command and Template Method Patterns, (cont d) Can implement the command steps as helper functions in the abstract Template Method base class, and allow subclasses to selectively use or not use them. Maintains fixed algorithm structure. If a step isn t used, it can be viewed as a no-op. Copyright c1997-2000 Dept. of Computer Science, Washington University 26 Copyright c1997-2000 Dept. of Computer Science, Washington University 27

Reducing the Number of Classes Back to Transactions The Template Method factors out common steps of an operation, but doesn t reduce the number of classes. We doubled the number of classes when we added atomicity to each Command, by using inheritance. Composition can often be a useful alternative to inheritance. And, it s useful to be able to add functionality without modifying existing classes. Transactions are composable May want to perform multiple operations, hierarchically composed Atomically, at various levels Consider disk backup operations at large companies, performed by a central organization: Need a boolean indication of whether the entire backup succeeded or failed If it failed, need to know where And, want to preserve any successful backup transactions Enter the Composite pattern Copyright c1997-2000 Dept. of Computer Science, Washington University 28 Copyright c1997-2000 Dept. of Computer Science, Washington University 29 The Composite Pattern Intent Compose (aggregate) objects, hierarchically, into tree structures. Represent any part of, or an entire, hierarchy Treat individual objects and recursive compositions uniformly Call an object or composition a component Structure of the Composite Pattern client Component operation () add (Component) remove (component) get_child (i) Resolves the following forces: Provide a uniform component interface, regardless of its internal complexity. Provide an extensible component interface Leaf operation () Composite operation () add (Component) remove (component) get_child (i) children iterate over children: i.operation () Copyright c1997-2000 Dept. of Computer Science, Washington University 30 Copyright c1997-2000 Dept. of Computer Science, Washington University 31

Composite Pattern Participants Composite Pattern Collaborations Component Provides the abstract interface for composed objects Leaf Concrete (primitive) Components Composite Non-leaf, concrete Components Client User of Composites, via the Component interface Clients call methods on objects, using the Component (abstract base class) methods If the object is a Leaf participant, it must have provided implementations for the abstract methods. Therefore, its methods are used. If the object is a Composite participant, then it can forward the method call to its subclass objects Using Iteration, for all subclass objects Copyright c1997-2000 Dept. of Computer Science, Washington University 32 Copyright c1997-2000 Dept. of Computer Science, Washington University 33 Example Uses of Composite Composite Pattern Summary GUIs, again. Compound graphical objects (shapes) are perfect examples. So are nested menus. Modelling manufacturing processes Assemblies are composed of subassemblies Compiler parse trees Structural Ties objects together, hierarchically Commonly used, like Iterator OO approaches factor out interface commonality into (abstract) base classes, to allow polymorphic treatment of instances Composite supports aggregation of objects with such common interfaces, allowing uniform treatment by users Nested transactions Together with Command pattern, to compose operations while supporting atomicity at various levels Copyright c1997-2000 Dept. of Computer Science, Washington University 34 Copyright c1997-2000 Dept. of Computer Science, Washington University 35