Download presentation
Presentation is loading. Please wait.
1
Observer pattern, MVC, IO & Files
Practical Session 6 Observer pattern, MVC, IO & Files
2
Observer pattern
3
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, …)
4
Recall ps4: 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 2 Register for an event E E 1 Act upon event 4 Receiver listener Send message to receiver 3
5
Exp: Event driven message passing
interface Clickable { public void onClick(); } interface Overable { public void onOver(); } Btn 1 Btn 2 Btn 3 Pseudo code Btn 1 (Clickable, Overable) void onClick() { teeter(); } Void onOver() { makeSound(CashRegister); Btn 2 (Clickable) void onClick() { spin(); } Btn 3 (Clickable, Overable) void onClick() { makeSound(Drum); } Void onOver() { makeSound(lazer); Register Send message Mouse listener registerForClick (Clickable f) { clickEventList.add(f); } registerForOver (Overable f) { overEventList.add(f); callRegisteredForClick () { for (Clickable c: clickEventList) c.onClick(); } callRegisteredForOver () { for (Overable o: overEventList) o.onOver(); } OverEventList btn 1 btn 3 clickEventList btn 2 Btn 3
6
Observer design pattern – Example 2
import java.util.ArrayList; import java.util.Scanner; class Subject { //Define Observer as an object with update(int int) // method public interface Observer { void update(int i1, int i2); } //Array of Observers private final ArrayList<Observer> observers = new ArrayList<>(); public void addObserver(Observer o) { observers.add(o); } private void notifyObservers(int i1, int i2) { for (Observer o: observers) o.update(i1, i2); } //Each read trigger notifications to all registered observers public void getUserInput() { Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) notifyObservers(scanner.nextInt(), scanner.nextInt()); } } //end Subject class
7
Observer design pattern – Example 2(Cont)
public class ObserverDemo { public static void main(String[] args) { Subject subject = new Subject(); //Add 1st observer subject.addObserver((i1, i2)->System.out.println("Add: " + (i1+i2))); //Add 2nd observer subject.addObserver((i1, i2)->System.out.println("Sub: " + (i1-i2))); //Add 3rd observer subject.addObserver((i1, i2)->System.out.println("I don’t care")); System.out.println("Enter two integers: "); subject.scanSystemIn(); } Enter 2 integers: 2 4 Add: 6 Sub: -2 I don't care 33 45 Add: 78 Sub: -12 Add: 200 Sub: 0 Run
8
MVC
9
MVC design pattern MVC – Model, View, Controller MVC design pattern
Specifies that an application consist of a data model, presentation information, and control information. Requires that each of these be separated into different objects.
10
MVC design pattern Model View Control
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.
11
MVC design pattern MVC – Different approaches but same main idea
12
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
13
MVC design pattern – Example
public class RectangleModel { private int len; private int width; public RectangleModel(int l, int w) {len=l; width=w; } public int getLen() { return len; } public void setLen(int l) { len=l; } public int getWidth() { return width; } public void setWidth(int w) { width=w; } } Model public class RectangleController { private RectangleModel model; private RectangleView view; public RectangleController(RectangleModel model, RectangleView view) { this.model = model; this.view = view; } public void updateView() { view.draw(model.getLen(), model.getWidth()); } public void setDim(int len, int width) { model.setLen(len); model.setWidth(width); } } Control public class RectangleView { 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("\nRect " + len + " X " + width); System.out.println(horiz); for (int i=0; i<width-2; i++) System.out.println(ver); System.out.println(horiz); } } View
14
MVC design pattern – Example (Cont)
I don't care MVC design pattern – Example (Cont) public class MVCDemo { public static void main(String[] args) { RectangleModel model = new RectangleModel(10, 5); //Simulate a database/model RectangleView view = new RectangleView(); RectangleController controller = new RectangleController(model, view); controller.updateView(); controller.setDim(20, 8); controller.updateView(); } Rect 10 X 5 ********** * * Rect 20 X 8 ******************** * * Run
15
IO & Files
16
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.getMessage()); System.err.println(e.getStackTrace()); } }
17
Must be handled within a try-catch block
Files Base operations Open file Read Write Close file File operations may cause exceptions File or directory not found No permissions No disk space Cannot close file In java usually by creating an object that handles the open, read/write and close Must be handled within a try-catch block
18
Files – Example: Write to file
public static void writeToFile() { System.out.println("Please insert filename:"); BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in)); try { String outFilename = inReader.readLine(); PrintWriter writer = new PrintWriter(outFilename); writer.println("Hello, World"); } catch (IOException e){ System.err.println(e.getMessage() + "\n" + e.getStackTrace()); } }
19
Files – Example: Read from file
public List<String> readAllLines(String path) { List<String> lines = new ArrayList<>(); try { BufferedReader reader = new BufferedReader(new FileReader(path)); String next; while ((next = reader.readLine()) != null) { lines.add(next); } } catch (FileNotFoundException e) { /* Handle FileNotFoundException */ } catch (IOException e) { /* Handle IOException */ return lines; }
20
Files – Example: Read from file
public List<String> readAllLines(String path) { List<String> lines = Collections.emptyList(); try { lines = Files.readAllLines(Paths.get(path)); } catch (IOException e) { /* Handle IOException */ } return lines; }
21
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 MyClass { public static void main(String[] args) { … } }
22
Command-line arguments
Adding arguments to your program is simple. The arguments are added after the name of your jar file, separated by spaces (‘ ‘).
23
Command-line arguments
This can also be done from your IDE, also separated by spaces (‘ ‘):
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.