Practical Session 6 Observer pattern MVC IO Files

Practical Session 6 Observer pattern, MVC, IO & Files

Observer pattern

Observer design pattern • A design pattern in which an object, the subject, maintains a list of its dependents, the observers, and notifies them automatically on state changes • The Observer design pattern helps: • Design flexible and reusable object-oriented software • Allows unlimited objects to be updated on object’s state changes • It is widely used to implement event handling systems (UI, Communication, …)

Recall ps 4: Event driven message passing • An event driven message is always given to a receiver object • The giver is often called the listener • The receiver send a message to the listener in order to register for an event of interest • The listener will pass a message when the event occurs • The receiver reacts in response to the message • The reaction is determined by the receiver Act upon event 1 4 Register for an event E E Receiver listener Send message to receiver 3 2

Exp: Event driven message passing Btn 2 (Clickable) void on. Click() { spin(); } click. Event. List Over. Event. List btn 1 btn 2 Btn 3 btn 1 btn 3 Btn 3 (Clickable, Overable) void on. Click() { make. Sound(Drum); } Void on. Over() { make. Sound(lazer); } de co Register Btn 1 (Clickable, Overable) void on. Click() { teeter(); } Void on. Over() { make. Sound(Cash. Register); } Mouse listener register. For. Click (Clickable f) { click. Event. List. add(f); } register. For. Over (Overable f) { over. Event. List. add(f); } Btn 3 Btn 2 Send message Btn 1 do eu Ps interface Clickable { public void on. Click(); } interface Overable { public void on. Over(); } call. Registered. For. Click () { for (Clickable c: click. Event. List) c. on. Click(); } call. Registered. For. Over () { for (Overable o: over. Event. List) o. on. Over(); }

Observer design pattern – Example 2 import java. util. Array. List; import java. util. Scanner; class Subject { private void notify. Observers(int i 1, int i 2) { for (Observer o: observers) o. update(i 1, i 2); } //Define Observer as an object with update(int int) // method public interface Observer { void update(int i 1, int i 2); } //Each read trigger notifications to all registered observers public void get. User. Input() { Scanner scanner = new Scanner(System. in); //Array of Observers private final Array. List<Observer> observers = new Array. List<>(); } } //end Subject class public void add. Observer(Observer o) { observers. add(o); } while (scanner. has. Next. Line()) notify. Observers(scanner. next. Int(), scanner. next. Int());

Observer design pattern – Example 2(Cont) public class Observer. Demo { public static void main(String[] args) { Subject subject = new Subject(); //Add 1 st observer subject. add. Observer((i 1, i 2)->System. out. println("Add: " + (i 1+i 2))); //Add 2 nd observer subject. add. Observer((i 1, i 2)->System. out. println("Sub: " + (i 1 -i 2))); //Add 3 rd observer subject. add. Observer((i 1, i 2)->System. out. println("I don’t care")); System. out. println("Enter two integers: "); subject. scan. System. In(); } Run Enter 2 integers: 24 Add: 6 Sub: -2 I don't care 33 45 Add: 78 Sub: -12 I don't care 100 Add: 200 Sub: 0 I don't care

MVC

MVC design pattern MVC – Model, View, Controller MVC design pattern 1. Specifies that an application consist of a data model, presentation information, and control information. 2. Requires that each of these be separated into different objects.

MVC design pattern Model • Contains only the pure application data • Can have logic to update controller if the data changes. • It has no information of how to present the data to a user. View • Presents the model’s data to the user. • It has no information of how to manipulate the mode’s date. Control • Exists between the view and the model. • Listens & reacts to events (triggered by the view or another external source) • In most cases, the event reaction is to call a method on the model.

MVC design pattern MVC – Different approaches but same main idea

MVC design pattern Advantages • Multiple developers can work simultaneously on the model, controller and views. • Logical grouping of related code • Models can have multiple views. Disadvantages • Complex – Requires more layers of abstraction

MVC design pattern – Example public class Rectangle. Model { private int len; private int width; public Rectangle. Model(int l, int w) {len=l; width=w; } public int get. Len() { return len; } public void set. Len(int l) { len=l; } public int get. Width() { return width; } public void set. Width(int w) { width=w; } } Model public class Rectangle. View { View public void draw(int len, int width) { String horiz = String. format("%0" + len + "d", 0). replace("0", "*"); String ver = String. format("*%" + (len-1) + "s", "*"); System. out. println("n. Rect " + len + " X " + width); System. out. println(horiz); for (int i=0; i<width-2; i++) System. out. println(ver); System. out. println(horiz); } } public class Rectangle. Controller { private Rectangle. Model model; private Rectangle. View view; Control public Rectangle. Controller(Rectangle. Model model, Rectangle. View view) { this. model = model; this. view = view; } public void update. View() { view. draw(model. get. Len(), model. get. Width()); } } public void set. Dim(int len, int width) { model. set. Len(len); model. set. Width(width); }

I don't care MVC design pattern – Example (Cont) public class MVCDemo { Rect 10 X 5 ***** public static void main(String[] args) { Rectangle. Model model = new Rectangle. Model(10, 5); //Simulate a database/model Rectangle. View view = new Rectangle. View(); Rectangle. Controller controller = new Rectangle. Controller(model, view); controller. update. View(); } controller. set. Dim(20, 8); controller. update. View(); * * * ***** Run Rect 20 X 8 ********** * * **********

IO & Files

I/O System. out – standard output stream System. in – standard input stream System. err – standard error stream Example public static void echo () { int ch; try { System. out. print("Enter some text: "); while ((ch = System. in. read()) != 'n') System. out. print((char) ch); } } catch (Exception e) { System. err. println(e. get. Message()); System. err. println(e. get. Stack. Trace()); }

Files Base operations • • Open file Read Write Close file In java usually by creating an object that handles the open, read/write and close • File operations may cause exceptions • • File or directory not found No permissions No disk space Cannot close file Must be handled within a try-catch block

Files – Example: Write to file public static void write. To. File() { } System. out. println("Please insert filename: "); Buffered. Reader in. Reader = new Buffered. Reader(new Input. Stream. Reader(System. in)); try { String out. Filename = in. Reader. read. Line(); Print. Writer writer = new Print. Writer(out. Filename); writer. println("Hello, World"); } catch (IOException e){ System. err. println(e. get. Message() + "n" + e. get. Stack. Trace()); }

Files – Example: Read from file public List<String> read. All. Lines(String path) { List<String> lines = new Array. List<>(); try { Buffered. Reader reader = new Buffered. Reader(new File. Reader(path)); String next; while ((next = reader. read. Line()) != null) { lines. add(next); } } catch (File. Not. Found. Exception e) { /* Handle File. Not. Found. Exception */ } catch (IOException e) { /* Handle IOException */ } return lines; }

Files – Example: Read from file public List<String> read. All. Lines(String path) { List<String> lines = Collections. empty. List(); try { lines = Files. read. All. Lines(Paths. get(path)); } catch (IOException e) { /* Handle IOException */ } return lines; }

Command-line arguments • The command line arguments are the arguments passed to a program at the time when you run it. • To access the command-line arguments inside a java program is quite easy, they are stored as string in String array passed to the args parameter of main() method. public class My. Class { } public static void main(String[] args) { … }

Command-line arguments • Adding arguments to your program is simple. • The arguments are added after the name of your jar file, separated by spaces (‘ ‘).

Command-line arguments • This can also be done from your IDE, also separated by spaces (‘ ‘):
- Slides: 23