日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

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

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

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

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

定義

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

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

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

模式應用前案例

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

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

結構

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

迭代器模式的上述結構是一個通用的結構,其代碼實現如下。Mb328資訊網——每日最新資訊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語言已經內置迭代器實現。上面的銀行領域案例,如果應用迭代器模式,代碼實現如下。Mb328資訊網——每日最新資訊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對象就可以依次訪問集合中的元素。Mb328資訊網——每日最新資訊28at.com

適用場景

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

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

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

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

模式可能存在的困惑

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

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

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

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

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

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

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

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

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

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

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

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

本質

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

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

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

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

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

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

標簽:
  • 熱門焦點
Top 主站蜘蛛池模板: 贵定县| 佛山市| 南木林县| 延长县| 江津市| 库车县| 辽中县| 西丰县| 汨罗市| 岳阳市| 平遥县| 蒙自县| 邓州市| 金昌市| 茶陵县| 大洼县| 通许县| 伊吾县| 潮州市| 荣昌县| 禄劝| 陇川县| 调兵山市| 青河县| 隆回县| 留坝县| 古浪县| 东乡县| 乌什县| 大英县| 安康市| 彩票| 寿光市| 深水埗区| 西丰县| 巴楚县| 武隆县| 桃江县| 璧山县| 贺兰县| 洛阳市|