Head-First Design Patterns. Similar to a ReminderEntry.

Slides:



Advertisements
Similar presentations
Continuation of chapter 6…. Nested while loop A while loop used within another while loop is called nested while loop. Q. An illustration to generate.
Advertisements

The Singleton Pattern II Recursive Linked Structures.
Java Review Interface, Casting, Generics, Iterator.
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
Chapter 7 Iterators Modified. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using.
Jan Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
50.003: Elements of Software Construction Week 8 Composing Thread-safe Objects.
1 TCSS 360, Spring 2005 Lecture Notes Design Patterns: Singleton, Memento, Flyweight.
Effective Java: Generics Last Updated: Spring 2009.
Nested References 2 inner reference data types Classes-Interfaces.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 8, page 1 Sun Certified Java 1.4 Programmer Chapter 8 Notes Gary Lance
Java I/O Writing and Reading Objects to File Serialization.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
CS1101 Group1 Discussion 7 Lek Hsiang Hui comp.nus.edu.sg
Static?. Static Not dynamic class Widget { static int s; int d; // dynamic // or instance // variable }
FOR LOOP WALK THROUGH public class NestedFor { public static void main(String [] args) { for (int i = 1; i
Interfaces and Inner Classes
Access Modifiers Control which classes use a feature Only class-level variables may be controlled by access modifiers Modifiers 1. public 2. protected.
Inheritance Type/Subtype Relationship. Inheritance Idea: An object B of one type, termed child class, inherits from another object A of another type,
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
Sit-In Lab 2 - OOP Restaurant.  Manage a restaurant and perform these types of queries: Assign a favorite table to a specific group Assign the lexicographically-smallest.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Arrays-. An array is a way to hold more than one value at a time. It's like a list of items.
Singleton Pattern Presented By:- Navaneet Kumar ise
Iterator Pattern. Traversing two different collections  When bringing two previously developed objects together, it can be difficult to change an implementation.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
Computer Science II 810:062 Section 01 Session 2 - Objects and Responsibilities.
System Programming Practical Session 4: Concurrency / Safety.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Files and Serialization. Files Used to transfer data to and from secondary storage.
Mid-Year Review. Coding Problems In general, solve the coding problems by doing it piece by piece. Makes it easier to think about Break parts of code.
Cs205: engineering software university of virginia fall 2006 Programming Exceptionally David Evans
1 Queues (Continued) Queue ADT Linked queue implementation Array queue implementation Circular array queue implementation Deque Reading L&C , 9.3.
XSLT in Practice. Exercises  download Apache Xalan - install it - try the example in Xalan-Java Overview  ZVON XSLT Tutorial.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
1 Iterator Pattern (A Behavioral Pattern) Prepared by: Neha Tomar.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Iterators. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using iterators to solve.
Repetition Statements
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
Memento Design Pattern
Chapter 16 Iterators.
Chapter 7 Iterators.
null, true, and false are also reserved.
Object Serialization Explanation + Example of file + network
More on Thread Safety CSE451 Andrew Whitaker.
Lecture Notes – Week 4 Chapter 5 (Loops).
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
Building Java Programs
Podcast Ch23f Title: Serialization
Threads in Java James Brucker.
Threads and Multithreading
The command invocation protocol
Threads CSE451 Andrew Whitaker TODO: print handouts for AspectRatio.
Threads and concurrency / Safety
Presentation transcript:

Head-First Design Patterns

Similar to a ReminderEntry

Similar to Reminders But no iterator. Just the raw data structure, i.e., ArrayList. To use this, outsider will have to keep index, increment it, etc. And they can change it!

How to use raw Get raw here. Set up loop here.

Use Iterator instead Much cleaner. Don’t need to know what data structure is being used. Just need to know I can use next and hasNext. And no access to raw! What work do we have to do to make this so easy in above code? 1.define createIterator method in BreakfastMenu class. 2.Figure out how to define that Iterator class that’s doing all the work.

The hard way: define your own Iterator class Would be similar to defining a RemindersIterator class. I *think* this code is poorly designed! Why? Because is does not clone the list from what I can see.

Code to show the strangeness DinerMenu dmenu = new DinerMenu(); DinerMenuIterator dit1 = dmenu.createIterator(); boolean b1 = dit1.hasNext();//should be false dmenu.add(“some new entry”); DinerMenuIterator dit2 = dmenu.creatIterator(); boolean b2 = dit2.hasNext();//should be true //Big question b1 = dit1.hasNext();//I predict will be true now Solution? public DinerMenuIterator createIterator(){ return new DinerMenuIterator( menuItems.clone() ); } Takes a “snapshot” of the data. If changes made later, snapshot is unchanged.

The easy way: look at data structure API! Data StructureMethod to return iterator ArrayList.iterator() LinkedList.iterator() Vector.iterator() arrayClass ArrayIterator …… Note that these methods do not clone either. If you want a snapshot, you will have to do something like: return my_linkedlist.clone().iterator();

Another Chapter

How to use it: Singleton s = Singleton.getInstance(); s.someMethod(); public void someMethod(){…} Access Levels ModifierClassPackageSubclassWorld publicYYYY protectedYYYN no modifier YYNN privateYNNN

Singleton Brings Up Concurrency Issues Many modern programs use multiple threads of control. This gives lots of power, e.g., multi-core, time- sharing in single-core. But it also brings up problems. Like to introduce you to one of them: concurrency bugs. Can use the Singleton pattern as example.

public class ThreadedClass extends Thread public void run(int i){ //this method runs when start() is invoked while( true ){ System.out.println( i ); } public static void main( String[] args ){ ThreadedClass t1 = new ThreadedClass(); t1.start(1); ThreadedClass t2 = new ThreadedClass(); t2.start(2); } What is printed? First Look at Thread class

public class ThreadedClass extends Thread static int data; public ThreadedClass(){ data = 0; } public void run(){ //this method runs when start() is invoked while( true ){ int k = data; k++; data = k; System.out.println( data ); } public static void main( String[] args ){ ThreadedClass t1 = new ThreadedClass(); t1.start(); ThreadedClass t2 = new ThreadedClass(); t2.start(); } What is printed? Gets more interesting. Opens the door for concurrency bugs. This will be shared by all threads.

while( true ){ t1 int k = data; k++; data = k; System.out.println( data ); } while( true ){ t2 int k = data; k++; data = k; System.out.println( data ); } t1: k 1 = 0 t1: k 1 = 1 t2: k 2 = 0 t2: k 2 = 1 t1: data = 1 t1: SOP 1 t2: data = 1 t2: SOP 1 t1: … t1: data = 1 t2: … t2: data = 2 t1: SOP 1 t2: SOP 2 ti: SOP 3 ti: SOP4 etc. What do we expect printed with two threads running? data

t1 t2 Who Cares? data t3 Where could this bite us in our project?

You can synchronize methods! Means only one thread at a time can use. Can’t break up into smaller chunks. Solves the concurrency bug we saw. Why is it expensive?

View as an annotation that says multiple threads might share this variable. Did we squash this concurrency bug?

One Other Idea

Serialization Issues public class Singleton implements java.io.Serializable { public final static Singleton INSTANCE = new Singleton(); private Singleton() { } } /////////////////////////////////////////////////////////////////////////////////////////// public class SingletonTest { public static void main(String [] args){ writeSingleton(); Singleton s1 = readSingleton(); Singleton s2 = readSingleton(); Assert.assertEquals(true, s1 == s2); } private static void writeSingleton() { FileOutputStream fos = new FileOutputStream("serializedSingleton"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(Singleton.INSTANCE); oos.flush(); } private static Singleton readSingleton() { Singleton s = null; FileInputStream fis = new FileInputStream("serializedSingleton"); ObjectInputStream ois = new ObjectInputStream(fis); s = (Singleton)ois.readObject(); return s; } true or false?

Work Around public class Singleton implements java.io.Serializable { public static Singleton INSTANCE = new Singleton(); protected Singleton() {} private Object readResolve() { return INSTANCE; } } The readResolve method is called when ObjectInputStream has read an object from the stream and is preparing to return it to the caller. ObjectInputStream checks whether the class of the object defines the readResolve method. If the method is defined, the readResolve method is called to allow the object in the stream to designate the object to be returned. The object returned should be of a type that is compatible with all uses. If it is not compatible, a ClassCastException will be thrown when the type mismatch is discovered.