Solution register itself

Similar documents
MIT AITI Swing Event Model Lecture 17

CSE 70 Final Exam Fall 2009

Commands. Written commands can be reused, cataloged, etc. Sometimes they also contain "undo" commands, too.

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

Part I: Learn Common Graphics Components

Design patterns for graphical user interface applications

The Observer Pattern

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Event Driven Programming

CS 251 Intermediate Programming GUIs: Event Listeners

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

SINGLE EVENT HANDLING

Introduction to Software Engineering (2+1 SWS) Winter Term 2009 / 2010 Dr. Michael Eichberg Vertretungsprofessur Software Engineering Department of

Studying software design patterns is an effective way to learn from the experience of others

GUI Applications. Let s start with a simple Swing application in Java, and then we will look at the same application in Jython. See Listing 16-1.

SampleApp.java. Page 1

Cheng, CSE870. More Frameworks. Overview. Recap on OOP. Acknowledgements:

Class 16: The Swing Event Model

Introduction to concurrency and GUIs

6 The MVC model. Main concepts to be covered. Pattern structure. Using design patterns. Design pattern: Observer. Observers

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS

EVENTS, EVENT SOURCES AND LISTENERS

Anonymous Classes. A short-cut for defining classes when you want to create only one object of the class.

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:

What Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { }

CS 170 Java Programming 1. Week 15: Interfaces and Exceptions

CSE 331. Model/View Separation and Observer Pattern

INF 111 / CSE 121. Homework 2: Design Patterns and Code Generation using Rational Software Development Platform

DCS235 Software Engineering Exercise Sheet 2: Introducing GUI Programming

Design Patterns and Frameworks Command

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Laboratorio di Tecnologie dell'informazione

Observer pattern. Somebody s watching me...

CS180 Recitation. More about Objects and Methods

Object Oriented Design & Patterns. Part 1

Design Patterns. it s about the Observer pattern, the Command pattern, MVC, and some GUI. some more

are most specifically concerned with

Model-View Controller IAT351

SYSC Come to the PASS workshop with your mock exam complete. During the workshop you can work with other students to review your work.

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions.

Programming Language Concepts: Lecture 8

DEMYSTIFYING PROGRAMMING: CHAPTER FOUR

Example: not good design. Motivation for MVC. public class BankAccount extends JPanel implements ActionListener

Original GUIs. IntroGUI 1

Global Gomoku Lab 4 in D0010E

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )

OOP Lab Factory Method, Singleton, and Properties Page 1

SE1021 Exam 2. When returning your exam, place your note-sheet on top. Page 1: This cover. Page 2 (Multiple choice): 10pts

GUI (Graphic User Interface) Programming. Part 2 (Chapter 8) Chapter Goals. Events, Event Sources, and Event Listeners. Listeners

Name: Checked: Learn about listeners, events, and simple animation for interactive graphical user interfaces.

Midterm assessment - MAKEUP Fall 2010

About This Lecture. Data Abstraction - Interfaces and Implementations. Outline. Object Concepts. Object Class, Protocol and State.

CSE 331 Software Design & Implementation

Case studies: Outline Case Study: Noughts and Crosses

FAQ: Classes & Objects

Systems Programming. Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid

Jonathan Aldrich Charlie Garrod

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1

University of Cape Town Department of Computer Science. Computer Science CSC117F Solutions

1.00/1.001 Introduction to Computers and Engineering Problem Solving Fall (total 7 pages)

Introduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014

COMP 401 Recitation 8. Observer Pattern

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Alex Mariakakis CSE 331, Autumn 2013 With material from Krysta Yousoufian, Marty Stepp, Mike Ernst, and others

(Incomplete) History of GUIs

Design Patterns Design patterns advantages:

02. OBSERVER PATTERN. Keep your Objects in the know. Don t miss out when something interesting happens

Composite Pattern - Shapes Example - Java Sourcecode

Swing from A to Z Some Simple Components. Preface

Binghamton University. CS-140 Fall Functional Java

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

Lecture 19 GUI Events

Introduction to Objects. James Brucker

University of Cape Town ~ Department of Computer Science. Computer Science 1016S / 1011H ~ January Exam

CS 106A, Lecture 25 Life After CS 106A, Part 1

CS342: Software Design. Oct 9, 2017

MVC: Model View Controller

User interfaces and Swing

RAIK 183H Examination 2 Solution. November 10, 2014

Java Interfaces Part 1 - Events Version 1.1

CMP 326 Midterm Fall 2015

Example: Building a Java GUI

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Example: Building a Java GUI

CS 180 Final Exam Review 12/(11, 12)/08

Object-Oriented Programming: Revision. Revision / Graphics / Subversion. Ewan Klein. Inf1 :: 2008/09

Interfaces and Polymorphism Advanced Programming

GUI Software Architecture

8. Polymorphism and Inheritance

Chapter 9. Interfaces and Polymorphism. Chapter Goals. Chapter Goals. Using Interfaces for Code Reuse. Using Interfaces for Code Reuse

Tuesday, October 4. Announcements

Project 1. LibraryTest.java. Yuji Shimojo CMSC 335

Guessing Game with Objects

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Graphical Interfaces

Lecture 4. Lecture

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

Lecture 9. Lecture

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Transcription:

Observer Pattern Context: One object (the Subject) is the source of events. Other objects (Observers) want to know when an event occurs. Or: several objects should be immediately updated when the state of one object changes, e.g. an editor with live preview.. Forces: We don't want the observers to poll for changes, which is inefficient. We don't want to complicate the Subject with a lot of code for event notification. (Not its purpose!)

Observer Pattern Solution: (1) Subject provides a method for Observer to register itself as wanting to receive event notification. (2) Subject calls a method when observers should be notified. (3) To avoid complicating the subject, implement the registration and event notification code in a separate class. This can be a superclass of the Subject, or another class that the Subject uses (delegate to it).

UML for Observer Pattern (1) Subject provides a method for Observers to register themselves as wanting to be notified of events. Method: addobserver( ) (2) Each Observer implements a known method (notify) for the Subject to invoke when an event occurs. Subject - observers: Collection +addobserver( Observer ) Observer +notify( event: Object )... +removeobserver(... ) ConcreteObserver +notify( event )... AnotheObserver +notify( event )... What are some examples of the Observer Pattern?

JButton uses Observer Subject: JButton is the source of events. Event: button press (an ActionEvent) Observer: any object that want to know when the button is pressed. How to implement: 1. Observer implements ActionListener, and defines an actionperformed( ) method. 2. Observer registers itself by calling button.addactionlistener( )

JButton Observers This observer counts button presses. /** An observer that counts button presses */ public class ClickCounter implements ActionListener { private int count = 0; } /** The event notification method. */ public void actionperformed(actionevent evt) { count += 1; System.out.println("Click number "+count); } public int getclickcount() { return count; }

Register the Observer We must add ClickCounter as an observer of the JButton. This is called registering an observer. JButton button = new JButton("Press Me"); frame.add(button); ClickCounter counter = new ClickCounter(); // register the observer button.addactionlistener( counter );

Benefits of using Observers 1. JButton is not coupled to the actual observer classes. JButton depends only on the interface for observers. 2. We can define and add new observers any time (extensible). 3. We can reuse the same observer for many components.

Table for Identifying a Pattern Name In Pattern Name in Application: this is for a JButton Subject Observer Concrete Observer JButton ActionListener a class that implements ActionListener addobserver( Observer ) addactionlistener( ) notify( Event ) [in the observer] actionperformed( ActionEvent ) notifyobservers [in Subject] fireactionperformed( )

Adding Observers to your App How can we apply the Observer Pattern to our code? Example: A UI for coin purse that tells us what the balance is.

Observer Pattern in Java Java provides an Observable class and Observer interface that make it easy to use the Observer pattern.. Observable - observers: Collection +addobserver( Observer ) +deleteobserver(... ) +notifyobservers( Object ) Observer +update( Observable, Object ) addobserver(this) -event( )... YourApplication YourObserver +update( observable, event )... void event( ) { setchanged( ); notifyobservers(obj);

Using the Observable class (1) Declare that your Subject class extends Observable public class MySubject extends Observable { /** An event the observers want to know about */ public void somethinghappened( ) { dosomework( ); // now notify the observers setchanged( ); notifyobservers( ); // can include a parameter } (2) When an event or change occurs, invoke setchanged() and notifyobservers()

Writing an Observer (3) Declare that observers implement the Observer interface. public class MyObserver implements Observer { /* This method receives notification from the * subject (Observable) when something happens * @param subject Observable that caused notif. * @param message is value of parameter sent * by subject. May be null. */ public void update( Observable subject, Object message ) { mysubject = (MySubject)subject;... } (4) update takes action using notification from the Subject.

Last Step: add Observers to Subject Call addobserver( ) to register the Observers with subject. public static void main(string [] args) { Observable subject = new MySubject( ); MyObserver observer = new MyObserver( ); } subject.addobserver( observer ); subject.run( );

Example for Coin Purse What are the interesting events? GUI observers Observable notifyobservers() extends insert( Money ) Purse withdraw( amt )

Purse with observer notification The purse should notify observers when the state of the purse changes. Draw a sequence diagram of what happens, using insert() as example.

C# Delegates as Observers Delegate is a type in the C# type system. It describes a group of functions with same parameters. Delegate can act as a collection for observers. /** define a delegate that accepts a string **/ public delegate void WriteTo( string msg ); /** create some delegates **/ WriteTo observers = new WriteTo( out.writeline ); observers += new WriteTo( button.settext ); observers += new WriteTo( textarea.append ); /** call all the observers at once! **/ observers("wake Up!");