Chào các em, chủ đề hôm nay của anh sẽ bàn về Design PatternIterator ? Khi nào chúng ta sẽ dùng nó trong lập trình.
1- Iterator Pattern là gì ?
Đây là pattern giúp chúng ta có thể duyệt qua tất các tập hợp một cách như nhau. Anh lấy ví dụ mình có thể lưu mảng 10 phần tử sinh viên trong mảng array, arraylist hoặc set. Do các mảng lưu trữ dữ liệu khác nhau như Array mình dùng index để lấy gía trị phần tử như student[1] còn ArrayList thì dùng method get(1). Như vậy có cách nào mà mình có thể duyệt qua mảng mà không quan tâm cấu trúc dữ liệu của nó là Array hay ArrayList không? Thì Iterator có thể làm được
2- Khi nào nên dùng Iterator
Chúng ta sử dụng Iterator khi chúng ta muốn duỵệt qua các phần tử trong tập hợp và không quan tâm cấu trúc nó là gì miễn là cài đặt đúng các phương thức của Iterator
3- Iterator UML
4- Iterator Code
Trong ví dụ sau đây mình sẽ viết một Iterator lấy các Profile của bạn mình và gửi tin nhắn tới các bạn của mình. Có thể các bạn của mình là dùng Facebook hoặc Twitter. Mình cũng dùng một phương pháp để duyệt qua danh sách. Mình không quan tâm bạn mình là dùng mạng xã hội nào miễn là cài đặt Iterator của mình là được.
Bước 1 : Tạo Interface Iterator có các phương thức duyệt qua mảng
Bước 2 : Các mạng xã hội facebook,twiter cài đặt chung một interface. Sau này chúng ta muốn có zalo hay bất cứ mạng xã hội nào chỉ cần cài đặt interface Profile Iterator thì mình đều có 1 duyệt phần tử y chang như các phương thức mình đã định nghĩa trong Iterator. Chứ mình không phải đập code hoặc viết thêm code cho phần zalo mà mình sử dụng cái đã có sẳn. Ở đây chú ý cho anh phương thức hasNext. Mỗi tập hợp phải tự cài đặt theo cách của mình. Khi nào anh gọi hasNext thì trả về cho anh phần tử tiếp theo.
Cũng như ví dụ về array và arraylist nếu 2 tập hợp này cùng cài đặt Iterator thì trong phương thức hasNext . Array và ArrayList phải tự viết theo cách của mình. Anh chỉ cần gọi hasNext thì sẽ nhận được phần tử tiếp theo.
publicclassProfile{privateStringname;privateStringemail;privateMap<String,List<String>>contacts=newHashMap<>();publicProfile(Stringemail,Stringname,String...contacts){this.email=email;this.name=name;// Parse contact list from a set of "friend:email@gmail.com" pairs.for(Stringcontact:contacts){String[]parts=contact.split(":");StringcontactType="friend",contactEmail;if(parts.length==1){contactEmail=parts[0];}else{contactType=parts[0];contactEmail=parts[1];}if(!this.contacts.containsKey(contactType)){this.contacts.put(contactType,newArrayList<>());}this.contacts.get(contactType).add(contactEmail);}}publicStringgetEmail(){returnemail;}publicStringgetName(){returnname;}publicList<String>getContacts(StringcontactType){if(!this.contacts.containsKey(contactType)){this.contacts.put(contactType,newArrayList<>());}returncontacts.get(contactType);}}
Mình giả lập mạng social network vì dụ như khi gọi lên facebook thì chờ một khoản thời gian, sau đó facebook trả lại kết quả 1 Profie người dùng cho mỉnh.
publicclassFacebookimplementsSocialNetwork{privateList<Profile>profiles;publicFacebook(List<Profile>cache){if(cache!=null){this.profiles=cache;}else{this.profiles=newArrayList<>();}}publicProfilerequestProfileFromFacebook(StringprofileEmail){// Here would be a POST request to one of the Facebook API endpoints.// Instead, we emulates long network connection, which you would expect// in the real life...simulateNetworkLatency();System.out.println("Facebook: Loading profile '"+profileEmail+"' over the network...");// ...and return test data.returnfindProfile(profileEmail);}publicList<String>requestProfileFriendsFromFacebook(StringprofileEmail,StringcontactType){// Here would be a POST request to one of the Facebook API endpoints.// Instead, we emulates long network connection, which you would expect// in the real life...simulateNetworkLatency();System.out.println("Facebook: Loading '"+contactType+"' list of '"+profileEmail+"' over the network...");// ...and return test data.Profileprofile=findProfile(profileEmail);if(profile!=null){returnprofile.getContacts(contactType);}returnnull;}privateProfilefindProfile(StringprofileEmail){for(Profileprofile:profiles){if(profile.getEmail().equals(profileEmail)){returnprofile;}}returnnull;}privatevoidsimulateNetworkLatency(){try{Thread.sleep(2500);}catch(InterruptedExceptionex){ex.printStackTrace();}}@OverridepublicProfileIteratorcreateFriendsIterator(StringprofileEmail){returnnewFacebookIterator(this,"friends",profileEmail);}@OverridepublicProfileIteratorcreateCoworkersIterator(StringprofileEmail){returnnewFacebookIterator(this,"coworkers",profileEmail);}}
publicclassLinkedInimplementsSocialNetwork{privateList<Profile>contacts;publicLinkedIn(List<Profile>cache){if(cache!=null){this.contacts=cache;}else{this.contacts=newArrayList<>();}}publicProfilerequestContactInfoFromLinkedInAPI(StringprofileEmail){// Here would be a POST request to one of the LinkedIn API endpoints.// Instead, we emulates long network connection, which you would expect// in the real life...simulateNetworkLatency();System.out.println("LinkedIn: Loading profile '"+profileEmail+"' over the network...");// ...and return test data.returnfindContact(profileEmail);}publicList<String>requestRelatedContactsFromLinkedInAPI(StringprofileEmail,StringcontactType){// Here would be a POST request to one of the LinkedIn API endpoints.// Instead, we emulates long network connection, which you would expect// in the real life.simulateNetworkLatency();System.out.println("LinkedIn: Loading '"+contactType+"' list of '"+profileEmail+"' over the network...");// ...and return test data.Profileprofile=findContact(profileEmail);if(profile!=null){returnprofile.getContacts(contactType);}returnnull;}privateProfilefindContact(StringprofileEmail){for(Profileprofile:contacts){if(profile.getEmail().equals(profileEmail)){returnprofile;}}returnnull;}privatevoidsimulateNetworkLatency(){try{Thread.sleep(2500);}catch(InterruptedExceptionex){ex.printStackTrace();}}@OverridepublicProfileIteratorcreateFriendsIterator(StringprofileEmail){returnnewLinkedInIterator(this,"friends",profileEmail);}@OverridepublicProfileIteratorcreateCoworkersIterator(StringprofileEmail){returnnewLinkedInIterator(this,"coworkers",profileEmail);}}
-Saukhilấyđượcdanhsáchngườidùngmìnhcóthểduyệtquabằngvònglệnhwhile(iterator.hasNext())đểkiểmtraxemđãduyệthếtcácphầntửchưa.publicclassSocialSpammer{publicSocialNetworknetwork;publicProfileIteratoriterator;publicSocialSpammer(SocialNetworknetwork){this.network=network;}publicvoidsendSpamToFriends(StringprofileEmail,Stringmessage){System.out.println("\nIterating over friends...\n");iterator=network.createFriendsIterator(profileEmail);while(iterator.hasNext()){Profileprofile=iterator.getNext();sendMessage(profile.getEmail(),message);}}publicvoidsendSpamToCoworkers(StringprofileEmail,Stringmessage){System.out.println("\nIterating over coworkers...\n");iterator=network.createCoworkersIterator(profileEmail);while(iterator.hasNext()){Profileprofile=iterator.getNext();sendMessage(profile.getEmail(),message);}}publicvoidsendMessage(Stringemail,Stringmessage){System.out.println("Sent message to: '"+email+"'. Message body: '"+message+"'");}}
publicclassDemo{publicstaticScannerscanner=newScanner(System.in);publicstaticvoidmain(String[]args){System.out.println("Please specify social network to target spam tool (default:Facebook):");System.out.println("1. Facebook");System.out.println("2. LinkedIn");Stringchoice=scanner.nextLine();SocialNetworknetwork;if(choice.equals("2")){network=newLinkedIn(createTestProfiles());}else{network=newFacebook(createTestProfiles());}SocialSpammerspammer=newSocialSpammer(network);spammer.sendSpamToFriends("anna.smith@bing.com","Hey! This is Anna's friend Josh. Can you do me a favor and like this post [link]?");spammer.sendSpamToCoworkers("anna.smith@bing.com","Hey! This is Anna's boss Jason. Anna told me you would be interested in [link].");}publicstaticList<Profile>createTestProfiles(){List<Profile>data=newArrayList<Profile>();data.add(newProfile("anna.smith@bing.com","Anna Smith","friends:mad_max@ya.com","friends:catwoman@yahoo.com","coworkers:sam@amazon.com"));data.add(newProfile("mad_max@ya.com","Maximilian","friends:anna.smith@bing.com","coworkers:sam@amazon.com"));data.add(newProfile("bill@microsoft.eu","Billie","coworkers:avanger@ukr.net"));data.add(newProfile("avanger@ukr.net","John Day","coworkers:bill@microsoft.eu"));data.add(newProfile("sam@amazon.com","Sam Kitting","coworkers:anna.smith@bing.com","coworkers:mad_max@ya.com","friends:catwoman@yahoo.com"));data.add(newProfile("catwoman@yahoo.com","Liza","friends:anna.smith@bing.com","friends:sam@amazon.com"));returndata;}}
Mọi người hãy Subscribe kênh youtube dưới đây nhé để cập nhật các video mới nhất về kỹ thuật và kỹ năng mềm