File tree Expand file tree Collapse file tree
pattern/src/com/premaseem Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11package com .premaseem ;
22
3- import java .util .List ;
4-
53/*
64@author: Aseem Jain
75@title: Design Patterns with Java 9
@@ -12,7 +10,23 @@ public static void main (String[] args) {
1210 System .out .println ("Iterator Pattern BEFORE CODE" );
1311
1412 FaceBook faceBook = new FaceBook ();
13+ Iterator faceBookIterator = faceBook .getIterator ();
14+
15+ // Loop over
16+ // init data with first(), keep increment with next()
17+ // and check termination condition with hasNext()
18+ for (faceBookIterator .first ();faceBookIterator .hasNext ();faceBookIterator .next ()){
19+ System .out .println (faceBookIterator .currentValue ());
20+ }
21+
22+ // $$$ Lesson Learned $$$
23+ // Loose coupling no need to know or import data structure
24+ // Data cannot be compromised ;-)
25+ // Provides limited control over data access
1526
27+
28+
29+ /* OLD CODE
1630 // Data structure is exposed
1731 List<String> friendsList = faceBook.getFriendsList();
1832
@@ -36,7 +50,7 @@ public static void main (String[] args) {
3650 for (int i = 0; i < friendsList.size(); i++) {
3751 System.out.println(friendsList.get(i));
3852 }
39-
53+ */
4054 // Lesson Learned
4155 // 1. Underlying Data structure is exposed
4256 // 2. Data can be manipulated
Original file line number Diff line number Diff line change 22
33import java .util .ArrayList ;
44import java .util .List ;
5+ import java .util .NoSuchElementException ;
56
67/*
78@author: Aseem Jain
@@ -20,7 +21,42 @@ public FaceBook () {
2021 friendsList .add ("Super Man" );
2122 }
2223
23- public List <String > getFriendsList () {
24- return friendsList ;
24+ // public List<String> getFriendsList () {
25+ // return friendsList;
26+ // }
27+
28+ public Iterator getIterator () {
29+ return new Iterator (this );
2530 }
2631}
32+
33+ class Iterator {
34+ private FaceBook faceBook ;
35+ private java .util .Iterator iterator ;
36+ private String value ;
37+
38+ public Iterator (FaceBook faceBook ) {
39+ this .faceBook = faceBook ;
40+ }
41+
42+ public void first () {
43+ iterator = faceBook .friendsList .iterator ();
44+ next ();
45+ }
46+
47+ public void next () {
48+ try {
49+ value = (String )iterator .next ();
50+ } catch (NoSuchElementException ex ) {
51+ value = null ;
52+ }
53+ }
54+
55+ public boolean hasNext () {
56+ return value != null ;
57+ }
58+
59+ public String currentValue () {
60+ return value ;
61+ }
62+ }
You can’t perform that action at this time.
0 commit comments