Class Notes (838,786)
Canada (511,086)
CSC207H1 (40)
Lecture

nov07c.docx

17 Pages
52 Views
Unlock Document

Department
Computer Science
Course
CSC207H1
Professor
Diane Horton
Semester
Fall

Description
NOVEMBER 07 • Design pattern: o A general description of the solution to a well-established problem using an arrangement of classes and objects o Patterns describe the shape of code rather than the details o They’re a means of communicating design ideas. o They are not specific to any one programming language. • Design pattern categories o Creational  Purpose: control the way objects are created  ex. Singleton, Abstract Factory, Prototype o Behavioral  Purpose: process a collection of items  ex. Iterator, Visitor o Structural  Purpose: store data in a particular way  ex. Composite, Adapter • Process List Pattern o Purpose: to process every item in a collection where you don’t care about order or context  doesn’t need to remember previous items. o Outline 1. for (Object o : list) { 2. // process o 3. } o Example 1. // print every time in a list 2. for (Object o : list) { 3. System.out.println(o) 4. } o Other example: dark every pixel in a picture  for pixel in pic: # etc. • Counted Loop Pattern o Purpose: to process a range of indices in a collection. o Outline 1. for (int i = 0; i != max index; i++) { 2. // process item at index i 3. } o Example 1. // Bubble through a list: swap items that are out of order. 2. for (int i = 0; i != list.size() - 1; i++) { 3. if (list.get(i) < list.get(i + 1)) { 4. swap(list, i, i + 1); // assuming helper function swap 5. } 6. } NOVEMBER 07 o Other example: dark every pixel in a picture  print indices of even-length strings • Accumulator Pattern o Purpose: to accumulate information about items in a collection o Outline 1. result = some appropriate base case, such as an empty list or 0 2. for (Object o : list) { 3. // Modify result with information from o. 4. } o Example 1. // Find the longest String in a list. 2. result = “”; 3. for (String s : list) { 4. if (s.length() > result.length()) { 5. result = s; 6. } 7. } o Other example: sum, min, accumulate a list of items meeting a particular criterion • Sentinel Pattern o Purpose: Search for a value without having to check in the loop guard whether you’ve gone past the end of the list. o Outline 1. add a “sentinal” item with a particular value at the end of the list 2. int i = 0; 3. while (list.get(i) != sentinel) { 4. i++; 5. } 6. remove the sentinel from the end o Example 1. // find the index of o in list, if it’s there. 2. list.add(o); // make sure o is in list. 3. int i = 0; 4. while (!o.equals(list.get(i))) { 5. i++; 6. } 7. list.remove(list.size() J 1); // remove the sentinel 8. // if i == list.size(), o was not in the list. o What the code would be like without a sentinel  first condition of while loop i != list.size() is evaluated every time through the loop, even when its false only once  very taxing on performance, especially given large loops 1. // find the index of o in list, if it’s there. 2. int i = 0; 3. while (i != list.size() && !o.equals(list.get(i))) { 4. i++; NOVEMBER 07 5. } 6. // if i == list.size() J 1, o was not in the list. • Observer o Purpose: to allow multiple objects to observe when another object changes. o Outline  class needs to extend java.util.Observable for its instance to be observable; inherits these methods:  void addObserver(Observer o)  boolean hasChanged()  void notifyObservers()  class needs to implement java.lang.Observer for its instances to be able to observer observable objects; implements these methods:  void update(Observable o, Object arg) o Uses  as an alternative (or enhancement) to MVC where each view observes the model o Example: Course.Java observed by Professor.Java objects and Department.java objects  Course.java 1. package obs_ex; 2. import java.util.Observable; 3. 4. class Course extends Observable { 5. 6. private int enrolmentCap; 7. private String name; 8. 9. public Course(String courseName, int initialCap) { 10. this.name = courseName; 11. this.enrolmentCap = initialCap; 12. } 13. 14. public String toString() { 15. return "Course: " + this.name + " with cap " + this.enrolmentCap; 16. } 17. 18. public void changeCap(int n) { 19. this.enrolmentCap += n; 20. setChanged(); 21. notifyObservers("Change to cap"); 22. } 23. }  Professor.java 1. package obs_ex; 2. import java.util.Observable; 3. import java.util.Observer; 4. 5. class Professor implements Observer { NOVEMBER 07 6. 7. private String name; 8. 9. public Professor(String name) { 10. this.name = name; 11. } 12. 13. @Override 14. public void update(Observable o, Object arg) { 15. System.out.println(this.name + 16. " just found out there was a change in " + o); 17. System.out.println(" The notification said: " + arg); 18. } 19. }  Department.java 1. package obs_ex; 2. 3. import java.util.Observable; 4. import java.util.Observer; 5. 6. class Department implements Observer { 7. 8. private String name; 9. 10. public Department(String name) { 11. this.name = name; 12. } 13. 14. public void update(Observable o, Object arg) { 15. System.out.println(this.name + 16. " just found out there was a change in " + o); 17. System.out.println(" The notification said: " + arg); 18. } 19. }  Main.java 1. package obs_ex; 2. 3. public class Main { 4. 5. public static void main(String[] args) { 6. Course csc207 = new Course("csc207", 120); 7. Course csc258 = new Course("csc258", 85); 8. Professor horton = new Professor("Diane Horton"); 9. Department dcs = new Department("Department of Computer Science"); 10. 11. csc207.addObserver(dcs); 12. csc207.addObserver(horton); NOVEMBER 07 13. csc258.addObserver(dcs); 14. csc207.changeCap(5); 15. } 16. }  Output >>> Diane Horton just found out there was a change in Course: csc207 with cap 125 >>> The notification said: Change to cap >>> Department of Computer Science just found out there was a change in Course: csc207 with cap 125 >>> The notification said: Change to cap • Singleton Pattern o Purpose: to ensure there is exactly one instance of a class. o Outline 1. public class NewSingleton { 2. private NewSingleton() { 3. } 4. 5. public static NewSingleton getInstance() { 6. return NewSingletonHolder.INSTANCE; 7. } 8. 9. private static class NewSingletonHolder { // inner class for the singleton 10. private static final NewSingleton INSTANCE = new NewSingleton(); 11. } 12. } o Uses: password verifier for a website, logger object for tracking events. o Example:  President.java 1. package singleton_ex; 2. 3. public class President { 4. 5. private String name; 6. 7. private President() { 8. System.out.println("President created."); 9. } 10. 11. public void setName(String name) { 12. this.name = name; 13. } 14. 15. public String toString() { NOVEMBER 07 16. return "The President of the United States, " + this.name; 17. } 18. 19. public static President getInstance() { 20. return PresidentHolder.INSTANCE; 21. } 22. 23. private static class PresidentHolder { 24. 25. private static final President INSTANCE = new President(); 26. } 27. }  PresidentVersion3.java 1. package singleton_ex; 2. 3. public class PresidentVersion3 { 4. 5. private static String name; 6. private static boolean oneExists = false; 7. 8. // You can complain about constructing multiples, but you can't stop 9. // the constructor from being thrown! 10. public PresidentVersion3() throws AttemptMultiplesException { 11. if (oneExists) { 12. throw new AttemptMultiplesException(); 13. } else { 14. System.out.println("New President created."); 15. oneExists = true; 16. } 17. } 18. 19. 20. public void setName(String name) { 21. this.name = name; 22. } 23. 24. public String getName() { 25. return this.name; 26. } 27. 28. @Override 29. public String toString() { 30. return "The President of the United States, " + this.name; 31. } 32. 33. public static void uselessWork() { 34. System.out.println("Hi ho!"); 35. } 36. NOVEMBER 07 37. }  AttemptMultipleException.java 1. package singleton_ex; 2. 3. public class AttemptMultiplesException extends Exception { 4. }  SingletonMain.java 1. package singleton_ex; 2. 3. public class SingletonMain { 4. 5. public static void main(String args[]) { 6. 7. try { 8. System.out.println("== Version 1"); 9. 10. // We can't construct an instance with new; the constructor is private! 11. // We get (and construct too) an instance using the getInstance method. 12. President p = President.getInstance(); 13. p.setName("Barack Obama"); 14. System.out.println(p); 15. 16. // We'll get the same one every time. 17. President q = President.getInstance(); 18. q.setName("Mitt Romney"); 19. System.out.println(q); 20. 21. // We changed his name, but it's the same object. 22. System.out.println("Same object? " + (p == q)); 23. 24. // Omitting a version 2 that does it another way. 25. 26. System.out.println("== Version 3"); 27. 28. PresidentVersion3 t = new PresidentVersion3(); 29. t.setName("Barack Obama"); 30. System.out.println(t); 31. 32. PresidentVersion3 u = new PresidentVersion3(); 33. u.setName("Mitt Romney"); 34. System.out.println(u); 35. System.out.println("Same object? " + (p == q)); 36. 37. } catch (AttemptMultiplesException e) { 38. System.out.println("You can't have more than one president."); 39. } 40. } NOVEMBER 07 41. }  Output >>> == Version 1 >>> == Version 3 >>> President created. >>> New President created. >>> The President of the United >>> The President of the United States, Barack Obama States, Barack Obama >>> The President of the United >>> You can't have more than one States, Mitt Romney president. >>> Same object? true • Iterator Pattern o Purpose: to separate the list contents from the object that iterates over them so that multiple iterators can be used. o Outline  interface java.util.Iterable: the collection of information, implements one method:  Iterator iterator()  interface java.util.Iterator: an object that knows the internals of that collection and can give them back one by one, implements these methods:  Object next()  boolean hasNext()  void remove() 1. Iterator itr = aList.iterator(); 2. while(itr.hasNext()) 3. // process itr.next() o Example: Implementing the Iterator Pattern 1. public class MyCollection implements Iterable { 2. private int size; 3. private T[] list = ...; 4. 5. public Iterator iterator() { 6. return new MyIterator(); 7. } 8. 9. private class MyIterator implements Iterator { 10. int current = 0; 11. 12. public boolean hasNext() { 13. return current < list.size(); 14. } 15. 16. public T next() { 17. T res = list.get(current); 18. current++; 19. return res; 20. } 21. // optional operation; what are the difficulties? 22. public void remove() { NOVEMBER 07 23. // not implemeneted yet 24. } 25. } 26. } o Example: array list iterator ArrayListIteratorExample.java 1. package iterator_ex; 2. 3. import java.util.ArrayList; 4. import java.util.Iterator; 5. import java.util.List; 6. 7. public class ArrayListIteratorExample { 8. 9. public static void main(String[] args) { 10. 11. List aList = new ArrayList(); 12. aList.add(1); 13. aList.add(2); 14. aList.add(3); 15. for (int i = 0; i != aList.size(); i++) { 16. System.out.println(aList.get(i)); 17. } 18. 19. System.out.println("=========="); 20. for (Object v : aList) { // This form of for-loop depends on an iterator. 21. System.out.println(v); 22. } 23. 24. Iterator myIterator = aList.iterator(); // ask an ArrayList to give us its iterator 25. System.out.println("=========="); 26. while (myIterator.hasNext()) { // and use its methods directly. 27. System.out.println(myIterator.next()); 28. } 29. 30. // Start back at the beginning, and this time, remove each item as we go. 31. myIterator = aList.iterator(); 32. System.out.println("========== Start again"); 33. while (myIterator.hasNext()) { 34. System.out.println(myIterator.next()); 35. myIterator.remove(); 36. } 37.
More Less

Related notes for CSC207H1

Log In


OR

Join OneClass

Access over 10 million pages of study
documents for 1.3 million courses.

Sign up

Join to view


OR

By registering, I agree to the Terms and Privacy Policies
Already have an account?
Just a few more details

So we can recommend you notes for your school.

Reset Password

Please enter below the email address you registered with and we will send you a link to reset your password.

Add your courses

Get notes from the top students in your class.


Submit