Tirgul 4

Tirgul 4

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 ( ):

Recently Viewed Presentations

  • MIS341 SYSTEM ANALYSIS &amp; DESIGN I - Experts Mind

    MIS341 SYSTEM ANALYSIS & DESIGN I - Experts Mind

    Fixed-Position Layout. Project remains in one place and workers and equipment come to site. E.g.: ship, highway, bridge, house, operation room. Complicating factors. Limited space at site. Different materials required at different stages of the project
  • Andrew Goodwin - Lordswood Media GCSE and A Level Resource Zone

    Andrew Goodwin - Lordswood Media GCSE and A Level Resource Zone

    Her music videos are instantly recognisable due to her trademark fashion sense. Amy Winehouse has also created her star image with the classical 'beehive' hair-do and flicking eye makeup that she wore everywhere without fail: her music videos, live performances...
  • Properties of Magma - KSU Faculty

    Properties of Magma - KSU Faculty

    Properties of Magma Physical & Chemical Properties An element is a substance that cannot be broken down into other substances (ex. Carbon, Hydrogen, Oxygen). A compound is a substance made of 2 or more elements that have been chemically combined...
  • LinkOut Update - National Center for Biotechnology Information

    LinkOut Update - National Center for Biotechnology Information

    Update Y. Kathy Kwan LinkOut Coordinator NCBI/NLM/NIH Medical Library Association Annual Meeting 2007 Philadelphia, PA NCBI/NLM/NIH Participants LinkOut Libraries: a global village Usage Full Text Links in > 8.2 M Citations (>5800 journals) What is New?
  • Early intervention in Ireland: the DETECT experience Ms.

    Early intervention in Ireland: the DETECT experience Ms.

    Early intervention in Ireland: the DETECT experience Ms. Laoise Renwick & Mr Shane Hill DETECT services * * * * * * * * * * * * * * Fair city is a popular Irish TV programme a bit...
  • Current Research in Ground Transportation

    Current Research in Ground Transportation

    Airport Ground Transportation Association Fall Conference Fort Worth, Texas September 11, 2007 Prepared by Peter B. Mandle Jacobs Consultancy Outline Airport Cooperative Research Program Current ACRP projects related to: Airport terminals People movers/walkways Parking and roadways Synthesis—GT Rules Other research...
  • CS206 --- Electronic Commerce

    CS206 --- Electronic Commerce

    CREATE ASSERTION FewBar CHECK ( (SELECT COUNT(*) FROM Bars) <= (SELECT COUNT(*) FROM Drinkers) ); Timing of Assertion Checks In principle, we must check every assertion after every modification to any relation of the database. A clever system can observe...
  • Logarithms - University of Washington

    Logarithms - University of Washington

    As the numbers get smaller and smaller, their logs approach negative infinity. The logarithm is not defined for negative numbers. Numbers not exact powers of 10 Logarithms are defined for all positive numbers. Since Log (100) = 2 and Log...