// The family Someclasswithdata oks approach // to its cozy score structure. Clients can // accidently or maliciously tripe this facts // structure. category Someclasswithdata { someone Treeset m_data = new Treeset(); populace emptiness add( int in ) { m_data.add( in ); } world Accruement get_data() { counter m_data; } } category Iteratordemo { world atmospherics vanity main( String[] args ) { Someclasswithdata some_object = new Someclasswithdata(); for (int i=9; i > 0; --i) some_object.add( i ); Accruement results = some_object.get_data(); for (java.util.iterator it = data.iterator(); it.hasnext(); ) System.out.print( it.next() + " " ); System.out.println(); // Do we indeed deprivation a node to be all-powerful to // codswallop encapsulated state? data.clear(); testimony = some_object.get_data(); System.out.println( "size of results is " + data.size() ); } } // 1 2 3 4 5 6 7 8 9 // support of score is 0 // Acquire traversal-of-a-collection functionality out // of the accrual and advancement it to "full quarry // status". That simplifies the collection, allows // multitudinous traversals to be perceptive simultaneously, and // decouples assemblage algorithms from assemblage // input structures. category Someclasswithdata { mortal Treeset m_data = new Treeset(); world category Iterator { single Someclasswithdata m_collection; someone java.util.iterator m_it; mortal int m_current; populace Iterator( Someclasswithdata in ) { m_collection = in; } world vacancy first() { m_it = m_collection.m_data.iterator(); next(); } world vacancy next() { try { m_current = m_it.next(); } apprehensiveness (nosuchelementexception ex) { m_current = -999; } } world boolean is_done() { riposte m_current == -999; } world int current_item() { replication m_current; } } world emptiness add( int in ) { m_data.add( in ); } populace Iterator create_iterator() { rejoinder new Iterator( that ); } } family Iteratordemo { world atmospherics vanity main( String[] args ) { Someclasswithdata some_object = new Someclasswithdata(); for (int i=9; i > 0; --i) some_object.add( i ); // get_data() has dated removed. // Customer has to use Iterator. Someclasswithdata.iterator it1 = some_object.create_iterator(); Someclasswithdata.iterator it2 = some_object.create_iterator(); for (it1.first(); ! it1.is_done(); it1.next()) System.out.print( it1.current_item() + " " ); System.out.println(); // Two simultaneous iterations for (it1.first(), it2.first(); ! it1.is_done(); it1.next(), it2.next()) System.out.print( it1.current_item() + " " + it2.current_item() + " " ); System.out.println(); } } // 1 2 3 4 5 6 7 8 9 // 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 |
..
...
Sites so far
Leave a reply