AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

一文徹底搞明白迭代器模式

來源: 責編: 時間:2024-05-16 09:10:22 154觀看
導讀本篇講解Java設計模式中的迭代器模式,分為定義、模式應用前案例、結構、模式應用后案例、適用場景、模式可能存在的困惑和本質探討7個部分。定義迭代器模式提供一種方法順序訪問一個聚合對象中的各個元素,而又不需暴露

本篇講解Java設計模式中的迭代器模式,分為定義、模式應用前案例、結構、模式應用后案例、適用場景、模式可能存在的困惑和本質探討7個部分。wpC28資訊網——每日最新資訊28at.com

定義

迭代器模式提供一種方法順序訪問一個聚合對象中的各個元素,而又不需暴露該對象的內部表示。wpC28資訊網——每日最新資訊28at.com

在新的分類方式中,迭代器模式被劃分至類之間的交互類別中,其簡化的是調用方對一個或一組對象遍歷行為的交互。wpC28資訊網——每日最新資訊28at.com

wpC28資訊網——每日最新資訊28at.com

模式應用前案例

在銀行業務領域中,銀行包含很多客戶,而一個客戶又可能包含多個賬戶。下面以這個案例進行說明。先來看一下未使用迭代器模式之前的代碼實現。wpC28資訊網——每日最新資訊28at.com

public class Account {//賬戶類private final String accountNumber;private final double balance;public Account(String accountNumber, double balance) {this.accountNumber = accountNumber;this.balance = balance;    }// 省略其他屬性和方法public String getAccountNumber(){return this.accountNumber;    }public double getBalance(){return this.balance;    }}public class Customer {//客戶類private final String name;private final List<Account> accounts;public Customer(String name) {this.name = name;this.accounts = new ArrayList<>();    }public void addAccount(Account account) {this.accounts.add(account);    }// 遍歷賬戶信息public void displayAccounts() {        System.out.println("Customer: " + this.name);//for (Account account : this.accounts) {//底層使用Iterator實現for(int i=0;i<this.accounts.size();i++) {            System.out.println("Account Number: " + this.accounts.get(i).getAccountNumber() + ", Balance: " + this.accounts.get(i).getBalance());        }    }}public class Bank {//銀行集合類private final List<Customer> customers;public Bank(){this.customers = new ArrayList<>();    }// 添加顧客public void addCustomer(Customer customer){this.customers.add(customer);    }// 顯示所有客戶的帳號信息public void displayAllCustomersAndAccounts() {//for (Customer customer : this.customers) {//底層使用Iterator實現for(int i=0;i<this.customers.size();i++) {this.customers.get(i).displayAccounts();        }    }}public class Client {//調用方代碼public static void main(String[] args) {        Bank bank= new Bank();        Customer customer1 = new Customer ("Sun");        customer1.addAccount(new Account( "1234" ,1000.0));        customer1.addAccount(new Account( "5678",500.0));        Customer customer2 = new Customer("Wang");        customer2.addAccount(new Account( "9012" ,200.0));        customer2.addAccount(new Account( "3456",40000));        bank.addCustomer(customer1);        bank.addCustomer(customer2);        bank.displayAllCustomersAndAccounts();    }}

對于迭代器模式,Java語言中的集合已經內置支持。在上述代碼中,注釋掉的增強的for循環方式(如for (Account account : this.accounts)),其底層也會轉換成Iterator方式。wpC28資訊網——每日最新資訊28at.com

因此,主要是對比for(int i=0;i<size;i++)這種方式和Iterator迭代器方式之間的優劣。wpC28資訊網——每日最新資訊28at.com

結構

wpC28資訊網——每日最新資訊28at.com

迭代器模式的上述結構是一個通用的結構,其代碼實現如下。wpC28資訊網——每日最新資訊28at.com

public interface Iterator<T> {T next();boolean hasNext();}public class ConcreteIterator<T> implements Iterator {private int currentIndex = 0;private T[] t;public ConcreteIterator(T[] t) {this.t = t;    }@Overridepublic Object next() {return t[currentIndex++];    }@Overridepublic boolean hasNext() {return currentIndex < t.length;    }}public interface Aggregate {Iterator createIterator();}public class ConcreteAggregate implements Aggregate {public String[] items;public ConcreteAggregate() {        items = new String[10];for(int i=0;i<items.length;i++) {            items[i] = "str"+i;        }    }@Overridepublic Iterator createIterator() {return new ConcreteIterator<String>(items);    }}public class Client {public static void main(String[] args) {        ConcreteAggregate aggregate = new ConcreteAggregate();        Iterator<String> iterator =  aggregate.createIterator();while (iterator.hasNext()) {            System.out.println(iterator.next());        }    }}

模式應用后案例

由于Java語言已經內置迭代器實現。上面的銀行領域案例,如果應用迭代器模式,代碼實現如下。wpC28資訊網——每日最新資訊28at.com

public class Account {//賬戶類private final String accountNumber;private final double balance;public Account(String accountNumber, double balance) {this.accountNumber = accountNumber;this.balance = balance;    }// 省略其他屬性和方法public String getAccountNumber(){return this.accountNumber;    }public double getBalance(){return this.balance;    }}public class Customer {//客戶類private final String name;private final List<Account> accounts;public Customer(String name) {this.name = name;this.accounts = new ArrayList<>();    }public void addAccount(Account account) {this.accounts.add(account);    }public Iterator<Account> iterator() {return this.accounts.iterator();    }public String getName() {return this.name;    }// 遍歷賬戶信息public void displayAccounts() {//循環賬戶        Iterator<Account> acctIterator = this.iterator();while(acctIterator.hasNext()){            Account acount = acctIterator.next();            System.out.println("Acount Number:"+acount.getAccountNumber() + ", Balance: "+acount.getBalance());        }    }}public class Bank implements Iterable<Customer>{private final List<Customer> customers;public Bank() {this.customers =new ArrayList<>();    }// 添加顧客public void addCustomer(Customer customer){this.customers.add(customer);    }@Overridepublic Iterator<Customer> iterator(){return this.customers.iterator();    }// 顯示所有客戶的帳號信息public void displayAllCustomersAndAccounts() {        Iterator<Customer> customerIterator = this.iterator();//循環客戶while(customerIterator.hasNext()) {            Customer customer = customerIterator.next();            System.out.println("Customer: " +customer.getName());            customer.displayAccounts();        }    }}public class Client {//調用方代碼public static void main(String[] args) {        Bank bank = new Bank();        Customer customer1 = new Customer("Sun");        customer1.addAccount(new Account("1234", 1000.0));        customer1.addAccount(new Account("5678", 500.0));        Customer customer2= new Customer ("Wang");        customer2.addAccount(new Account( "9012" ,200.0));        customer2.addAccount(new Account( "3456",40000));        bank.addCustomer(customer1);        bank.addCustomer(customer2);        bank.displayAllCustomersAndAccounts();    }}

Java語言中提供了Iterable接口,然后重寫里面的iterator方法。通過該方法就可以得到一個Iterator對象,然后可以利用這個Iterator對象就可以依次訪問集合中的元素。wpC28資訊網——每日最新資訊28at.com

適用場景

迭代器模式適用于以下場景:wpC28資訊網——每日最新資訊28at.com

1、訪問一個聚合對象的內容而無需暴露它的內部表示wpC28資訊網——每日最新資訊28at.com

2、支持對聚合對象的多種遍歷方式,如樹、圖等wpC28資訊網——每日最新資訊28at.com

3、對遍歷不同的聚合結構提供一個統一的接口wpC28資訊網——每日最新資訊28at.com

模式可能存在的困惑

困惑1:增強for循環(如for(obj:ObjList))與Iterator迭代器方式有何區別?wpC28資訊網——每日最新資訊28at.com

增強for循環方式相當于Java語言中的一種語法糖。在編譯階段,會轉換成Iterator方式實現。wpC28資訊網——每日最新資訊28at.com

困惑2:普通for循環(如for(int i=0;i<size;i++))似乎也比較簡潔,Iterator相比有什么優勢?wpC28資訊網——每日最新資訊28at.com

針對數組、鏈表等簡單的數據結構,兩種循環方式其實體現不出優勢。但是,對于樹和圖等復雜數據結構,普通for循環很難支持。wpC28資訊網——每日最新資訊28at.com

例如,對于樹(Tree)這類數據結構,至少包括以下三種遍歷方式:wpC28資訊網——每日最新資訊28at.com

1)前序遍歷(Preorder Traversal):先訪問根節點,然后遞歸地前序遍歷左子樹和右子樹;wpC28資訊網——每日最新資訊28at.com

2)中序遍歷(Inorder Traversal):先遞歸地中序遍歷左子樹,然后訪問根節點,最后遞歸地中序遍歷右子樹;wpC28資訊網——每日最新資訊28at.com

3)后序遍歷(Postorder Traversal):先遞歸地后序遍歷左子樹和右子樹,最后訪問根節點。wpC28資訊網——每日最新資訊28at.com

對于圖(Graph)這類數據結構,至少也要支持以下兩種遍歷方式wpC28資訊網——每日最新資訊28at.com

1)深度優先搜索(Depth-First Search, DFS):從起始頂點出發,在走過一條路徑上所有未被標記過的頂點之前不回退;wpC28資訊網——每日最新資訊28at.com

2)廣度優先搜索(Breadth-First Search, BFS):從起始頂點開始向外層擴散搜索,并且按照距離排序依次進行探索。wpC28資訊網——每日最新資訊28at.com

此外,由于迭代器是一個家族類,最上層是一個Iterable接口,后續也可以靈活擴展其他更高效的遍歷方式。wpC28資訊網——每日最新資訊28at.com

本質

對于一個類來說,對于其屬性或狀態的遍歷是類的一種行為。但是,這種行為不屬于核心業務操作。wpC28資訊網——每日最新資訊28at.com

因此,迭代器模式的本質上是將這種遍歷行為通用化,這樣也可以為調用方提供統一的訪問接口。wpC28資訊網——每日最新資訊28at.com

本文鏈接:http://www.tebozhan.com/showinfo-26-88392-0.html一文徹底搞明白迭代器模式

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 揭秘 Java 跨系統文件路徑組裝的秘方!

下一篇: Kafka六大使用場景以及核心概念,你知道幾個?

標簽:
  • 熱門焦點
  • 7月安卓手機好評榜:三星S23Ultra好評率第一

    性能榜和性價比榜之后,我們來看最后的安卓手機好評榜,數據來源安兔兔評測,收集時間2023年7月1日至7月31日,僅限國內市場。第一名:三星Galaxy S23 Ultra好評率:95.71%在即將迎來新
  • CSS單標簽實現轉轉logo

    轉轉品牌升級后更新了全新的Logo,今天我們用純CSS來實現轉轉的新Logo,為了有一定的挑戰性,這里我們只使用一個標簽實現,將最大化的使用CSS能力完成Logo的繪制與動畫效果。新logo
  • 在線圖片編輯器,支持PSD解析、AI摳圖等

    自從我上次分享一個人開發仿造稿定設計的圖片編輯器到現在,不知不覺已過去一年時間了,期間我經歷了裁員失業、面試找工作碰壁,寒冬下一直沒有很好地履行計劃.....這些就放在日
  • 重估百度丨“晚熟”的百度云,能等到春天嗎?

    &copy;自象限原創作者|程心排版|王喻可2016年7月13日,百度云計算戰略發布會在北京舉行,宣告著百度智能云的正式啟程。彼時的會場座無虛席,甚至排隊排到了門外,在場的所有人幾乎都
  • 慕巖炮轟抖音,百合網今何在?

    來源:價值研究所 作者:Hernanderz&ldquo;難道就因為自己的一個產品牛逼了,從客服到總裁,都不愿意正視自己產品和運營上的問題,選擇逃避了嗎?&rdquo;這一番話,出自百合網聯合創
  • 小米汽車電池信息疑似曝光:容量101kWh,支持800V高壓快充

    7月14日消息,今日一名博主在社交媒體發布了一張疑似小米汽車電池信息的照片,顯示該電池包正是寧德時代麒麟電池,容量為101kWh,電壓為726.7V,可以預測小
  • 超級標準版旗艦!iQOO 11S全球首發iQOO超算獨顯芯片

    上半年已接近尾聲,截至目前各大品牌旗下的頂級旗艦都已悉數亮相,而下半年即將推出的頂級旗艦已經成為了數碼圈爆料的主流,其中就包括全新的iQOO 11S系
  • Android 14發布:首批適配機型公布

    5月11日消息,谷歌在今天凌晨舉行了I/O大會,本次發布會谷歌帶來了自家的AI語言模型PaLM 2、谷歌Pixel Fold折疊屏、谷歌Pixel 7a手機,同時發布了Androi
  • OPPO K11評測:旗艦級IMX890加持 2000元檔最強影像手機

    【Techweb評測】中端機型用戶群體巨大,占了中國目前手機市場的大頭,一直以來都是各手機品牌的“必爭之地”,其中OPPO K系列機型一直以來都以高品質、
Top