1 / 26

Clients and Suppliers

Clients and Suppliers. The business of computer science. Clients and Suppliers. Two classes: May be related as client – supplier. May not be related as client – supplier. Client : The object that uses the services of the supplier to accomplish a complex task Supplier :

Download Presentation

Clients and Suppliers

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Clients and Suppliers The business of computer science

  2. Clients and Suppliers • Two classes: • May be related as client – supplier. • May not be related as client – supplier. • Client: • The object that uses the services of the supplier to accomplish a complex task • Supplier: • The object that provides data/services to the other object

  3. Averager - intcount - inttotal «constructor» + Averager() «update» + void clear() + void include( int ) «query» + double getAverage() + intgetIncludeCount() Supplier Example • Design a class that keeps statistical information about a bunch of numbers • average • standard deviation • min • max • others… • We’ll start with just ‘average’

  4. Averager - intcount - inttotal «constructor» + Averager() «update» + void clear() + void include( int ) «query» + double getAverage() + intgetIncludeCount() Supplier Example // code fragment that uses the Average class Averager sum1, sum2; sum1 = new Averager(); sum1.include( 10 ); sum1.include( 10 ); sum1.include( 3 ); sum1.include( 7 ); System.out.println(“Count: “+sum1.getIncludeCount()); System.out.println(“Average: “+sum1.getAverage()); sum2 = new Averager(); sum2.include( (int) Math.random()*10 ); sum2.include( (int) Math.random()*10 ); System.out.println(“Count: “+sum2.getIncludeCount()); System.out.println(“Average: “+sum2.getAverage());

  5. Averager - int count - int total «constructor» + Averager() «update» + void clear() + void include( int ) «query» + double getAverage() + int getIncludeCount() How to Implement? public class Averager { private int count; private int total; public Averager() { clear(); } public void clear() { count = 0; total = 0; } public void include( int d ) { total = total + d; count++; } public double getAverage() { return ((double)total) / count; } public int getIncludeCount() { return count; } }

  6. Supplier Example public class Die { private int value; public Die() { value = roll(); } public int roll() { value = 1 + Math.random() * 6; return value; } public intgetValue() { return value; } } Consider writing a Die class. The class should not be concerned with the way a Die ‘looks’ but with what a die ‘is’ and how it is used. • Generate a class diagram • Generate a class specification • Implement the class

  7. Supplier Example public class Die { private int value; private Averageraverager; public Die() { averager = new Averager(); value = roll(); } public int roll() { value = 1 + Math.random() * 6; averager.include(value); return value; } public intgetValue() { return value; } public double getAverage() { return averager.getAverage(); } public intgetNumberOfTimesRolled() { return average.getIncludeCount(); } } Consider writing a more feature-laden Die class. A Die can report on the average of every roll that IT has ever made and the total number of times it has been rolled.

  8. Client Supplier in UML Class Diagram • A client supplier relationship can be represented in a UML class diagram • A line connecting two boxes (classes) represents a relationship • A black diamond is connected to the client • No annotation is given on the suppliers end • Can be understood as ‘aggregation’

  9. 0 1 2 3 4 5 6 Indices Single char Single String The String Class • The String class is an example of a supplier • A String represents a sequence of chars (text!) • A char is one of the eight primitive types • A char represent a single keyboard character • a single textual symbol G o R a m s

  10. Strings • Strings are objects! • A sequence of characters (i.e. text) • Built-in class • Immutable • Can’t be altered or changed once created • Syntax: zero or more characters enclosed in double quotes “a” “Hello!” “3<true” “” Hi! “12” Image from: http://www.fabricattic.com/Buckaroo%20Bears%20blue%20rope.jpg

  11. String Behavior • What kind of operations should be supported by Strings? • length of string • “adding” two strings • comparing two strings • finding a char in the string • many others… Image from: http://www.fonsecatim.com/Vlume1d.JPG

  12. Strings • String “concatenation” • Indicated by a “+” • Computes a new string that joins two strings • public int length() • returns the number of characters in the sequence • public char charAt(int index) • returns the number of character at the specified index • public boolean equals(Object other) • returns true if the two strings are equals an false otherwise • public boolean startsWith(String other) • returns true if the calling string begins with the specified string • public String toLowerCase() • returns a new string that is an all lower-case representation of the calling • public String toUpperCase() • returns a new string that is an all upper-case representation of the calling • public String substring(int start, int end) • returns a new string that is a substring of original. Starting at start through end-1.

  13. Strings • public intindexOf(char c) • returns the index of the first occurrence of c or -1 if c does not occur • public booleanisEmpty() • returns true if the string has no characters (i.e. if the length is 0) • public char charAt(int index) • returns the number of character at the specified index • public booleanendsWith(String other) • returns true if the calling string ends with the specified string • public booleanequalsIgnoreCase(String other) • returns true if the calling string is equal to the other and case is not considered • public String replace(char oldChar, char newChar) • returns a new string where every oldChar has been replaced by newChar • public String trim() • returns a copy of the string with leading and trailing whitespace omitted

  14. String Concatenation • String concatenation is indicated by ‘+’ • binary infix operator • operands must be strings • if either operand is NOT a string, the operand is converted to a string and then the operation is performed String msg = “Hello World”; String msg2 = msg + 13; String msg3 = “V” + 8; String msg4 = 12 + ‘a’;

  15. String String msg = “Hello World”; int x = msg.length(); char c = msg.charAt(4); boolean b1 = msg.startsWith(“He”); String s1 = msg.toLowerCase(); String s2 = msg.toUpperCase(); String s3 = msg + “ again “ + ‘!’. boolean b2 = msg.equals(“hello world”);

  16. String Example • DNA are typically represented as strings • Composed of characters ‘C’, ‘A’, ‘G’, ‘T’ • C: Cytosine • A: Adenine • G: Guanine • T: Thymine • Example CAGGGGGTAC Image from: http://members.aol.com/wayneheim/dna-w.jpg

  17. String Processing • Problem: Write a function that accepts a string and returns “true” if the string is a DNA string and false otherwise. The method should be case insensitive. public booleanisDNAChar(char c) { return c == ‘C’ || c == ‘A’ || c == ‘G’ || c == ‘T’; } public booleanisDNA(String s) { for(inti=0; i<s.length() ; i++) { if(!isDNAChar(s.charAt(i))) return false; } return true; }

  18. String Processing • Problem: Write a function that accepts a string and returns true if the string is a palindrome and false otherwise. Example: given BACAB the method should return true (a mayan diety). Also try NAMAN. public booleanisPalindrome(String s) { for(inti=0; i<s.length()/2; i++) { int j=s.length()-i; if(s.chartAt(i) != s.chartAt(j)) return false; } return true; }

  19. String Processing • Problem: Write a function that accepts two strings and an integer. The function should “splice” the strings together, creating a new string which is S1[0]…S1[n-1]S2[n]…S2[end] Example: given CAGTCAGT and TGACTGAC and 3 you should return CAGCTGAC public String splice(String s1, String s2, int n) { return s1.substring(0, n) + s2.substring(n, s2.length()); }

  20. Access Control Modifiers • A class is a container for data and methods. The class is able to control access to these things via "access control modifiers" • public: any code anywhere has access • private: only code in the containing class has access • protected: we’ll talk about this when your older • Use public when the item is for external use • Use private when the method is only for internal use

  21. How to Design • Programmers generally discoverobjects by looking for data and operations that belong together. • How to design (discover) a supplier: • Determine the public methods (behavior) • Determine the private attributes (state) • Implement the public methods

  22. Supplier Example Draw a class diagram for a SavingsAccount class. public class SavingsAccount { private double balance; public SavingsAccount( double d) { balance = d; } public void makeDeposit(double d) { balance = balance + d; } public void makeWithdrawl(double d) { balance = balance - d; } public void compoundInterest(double r) { balance = balance * (1+ r / 100); } public double getBalance() { return balance; } } Write a client class that ... • Creates Sue’s savings account with an initial balance of $100.00 • Deposit $20.00 into Sues account • Withdraws $5.25 from Sues account • Adds compound interest of 6% • Prints the final balance • Creates Sam’s savings account with an initial balance of $30.00 • Adds compound interest to Sam’s account for two years at 5% • print Sam’s final balance

  23. bestVar scope privateMethod scope betterVar scope Scope Issues RULE: Hide as much information (from the client) as possible. public class MyClass { public int badVar; private int betterVar; public Myclass() { int bestVar; ... } public void publicMethod() { ... } private void privateMethod() { ... } }

  24. Design Issues The lifetime of an object is the portion of execution time between the object’s instantiation and the time it is orphaned (or the program terminates). The lifetime of primitive data follows its scope.  Local variable lifetime is the run time of a single method execution.  Formal parameter lifetime is the run time of a single method execution.  Instance variable lifetime is the lifetime of the containing object. The lifetime of reference data depends upon code execution. • A new expression begins a lifetime. • When a variable is assigned null, any object previously bound to that variable may end its lifetime. (When would this not end the • object’s lifetime? • What other instructions might orphan an object? (i.e., end its lifetime)

  25. Scope Design • RULE: Hide as much information (from the client) as possible! • Variables: • Use LOCAL whenever possible • Use PRIVATE only when data needs to be kept between method calls • Use PUBLIC – Almost Never! • Methods • Use PRIVATE whenever possible • Use PUBLIC if the client is meant to use it Image from: http://www.stecf.org/~rfosbury/home/natural_colour/spectroscopes/Browning_s-scope.gif

  26. Access to instance variables • Instance variables are almost always ‘private’ • How can clients know those values? • How can clients change those values? • Instance variables are made readable through accessors. • A method that returns the value. • Conventionally named “getX” • Instance variables are made changeable through settors. • A method that changes the value. • Conventionally named “setX”

More Related