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

  • Entertainment and Sport - waze

    Entertainment and Sport - waze

    Sport Popular sports in England: football ( = soccer ) rugby cricket golf tennis horse racing betting money on the winning horse Cricket Cricket a similar game was played in England 700 years ago competitions are held in summer matches...
  • Healthful Food/Beverage Stocking Levels for Small Retail Food ...

    Healthful Food/Beverage Stocking Levels for Small Retail Food ...

    This definition includes stores that sell a range of merchandise, including foods and beverages as well as other products, such as dollar stores and retail pharmacies. ... Varieties of staple products include but are not limited to whole grain bread,...
  • Traffic Management - FHWA Operations

    Traffic Management - FHWA Operations

    Traffic Management Team (State Force) Transportation Management Center (State Force) ... Construction time is shortened and all or a major par of the facility can be completely closed for all or parts of the day or week. For example, I-84...
  • Metric Units - Caldew School

    Metric Units - Caldew School

    mm cm dm m Dm hm km 1/1000 m 1/100 m 1/10 m 1 m 10 m 100 m 1000 m millimetre centimetre decimetre metre Decametre hectometre kilometre Units of Distance The principal unit of distance in the metric system...
  • eReaders in the Academic Library Richard Hayman Reference

    eReaders in the Academic Library Richard Hayman Reference

    eBooks in Canadian Academic Libraries. Expenditures on Electronic. Monographs as % of Total. Monographs. PRINT MONOGRAPHS. 12.7 87.3. In Canadian academic libraries, expenditures on electronicmonographs as a percentage of total monographs is 12.7% on average (mean).
  • Homework#1, Problem 1 - LSU

    Homework#1, Problem 1 - LSU

    The associated magnetic field are: AND Example, Treating a Changing Electric Field as a Displacement Current: Magnetic Moment vs. Magnetization 32.10: Paramagnetism: The ratio of its magnetic dipole moment to its volume V. is the magnetization M of the sample,...
  • 4.3 (Part 2) Economy

    4.3 (Part 2) Economy

    Traditional Economy Definition: System in which people grow their own food and make their own goods Trade may take place through barter, (definition: the exchange of goods without the use of money.) Often found in rural and remote communities Market...
  • The Outsiders - Liberty Hill J High School

    The Outsiders - Liberty Hill J High School

    The Outsiders. Vocabulary Warm-Up. Section 1. ... Feeling that you don't like or trust something . Aloof. Acting distant, indifferent. Rivalry. Competitionover a long period of time ... Now use your own words to fill in the sentence under the...