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 objects state changes It is widely used to implement event handling systems (UI, Communication, ) 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 Act upon event 1 4 2 Register for an event E E Receiver listener
Send message to receiver 3 Exp: Event driven message passing Btn 1 Btn 3 Btn 2 eu Ps interface Clickable { public void onClick(); } interface Overable {
public void onOver(); } clickEventList OverEventList btn 1 btn 2 Btn 3 btn 1 btn 3 Btn 3 (Clickable, Overable) void onClick() { makeSound(Drum); } Void onOver() { makeSound(lazer);
} de co Mouse listener registerForClick (Clickable f) { clickEventList.add(f); } registerForOver (Overable f) { overEventList.add(f); } Btn 2 (Clickable) void onClick() { spin(); } Send message
do Register Btn 1 (Clickable, Overable) void onClick() { teeter(); } Void onOver() { makeSound(CashRegister); } callRegisteredForClick () { for (Clickable c: clickEventList) c.onClick(); } callRegisteredForOver () { for (Overable o: overEventList) o.onOver(); }
Observer design pattern Example 2 import java.util.ArrayList; import java.util.Scanner; class Subject { private void notifyObservers(int i1, int i2) { for (Observer o: observers) o.update(i1, i2); } //Define Observer as an object with update(int int) // method public interface Observer { void update(int i1, int i2); } //Each read trigger notifications to all registered observers public void getUserInput() {
Scanner scanner = new Scanner(System.in); //Array of Observers private final ArrayList observers = new ArrayList<>(); } } //end Subject class public void addObserver(Observer o) { observers.add(o); } while (scanner.hasNextLine()) notifyObservers(scanner.nextInt(), scanner.nextInt()); 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 dont care")); System.out.println("Enter two integers: "); subject.scanSystemIn(); } Run Enter 2 integers: 24 Add: 6 Sub: -2 I don't care 33 45 Add: 78
Sub: -12 I don't care 100 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 models data to the user. It has no information of how to manipulate the modes 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 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 RectangleView { 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("\nRect " + len + " X " + width); System.out.println(horiz); for (int i=0; i
} public void setDim(int len, int width) { model.setLen(len); model.setWidth(width); } } I don't care MVC design pattern Example (Cont) Rect 10 X 5 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); * * * * * * ********** Run Rect 20 X 8
controller.updateView(); controller.setDim(20, 8); controller.updateView(); } ******************** * * * * * * *
* * * * * ******************** 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.getMessage()); System.err.println(e.getStackTrace()); } } 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 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()); } } Files Example: Read from file public List readAllLines(String path) { List 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; } Files Example: Read from file public List readAllLines(String path) { List lines = Collections.emptyList(); try { lines = Files.readAllLines(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 MyClass { 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 ( ):