迭代器模式
場景描述:我們目前正在吞併期,剛把一個煎餅店和一個餐廳兼併了。但是關於菜單的設計上好像遇到了寫麻煩,兩者採用的集合不同,一個用數組,一個用ArrayList。
嘗試:如果我們想要打印菜單,就需要分別對兩種不同的集合進行處理。
我們可以封裝遍歷嗎?不論是那種集合,我們都可以統一進行處理。
這就需要引出迭代器了。
public interface Iterator {
boolean hasNext();
Object next();
}
以及我們的菜單項格式
public class MenuItem {
public String name;
public String description;
public boolean vegetarian;
public double price;
public MenuItem(String name, String description, boolean vegetarian, double price){
this.name = name;
this.description = description;
this.vegetarian = vegetarian;
this.price = price;
}
public String getName(){
return name;
}
public String getDescription(){
return description;
}
public double getPrice() {
return price;
}
public boolean isVegetarian() {
return vegetarian;
}
}
然後我們分別爲不同的菜單設計不同的迭代器:
餐廳的
public class DinerMenu {
static final int MAX_ITEMS = 6;
int numberOfItems = 0;
MenuItem[] menuItems;
public DinerMenu(){
menuItems = new MenuItem[MAX_ITEMS];
addItem("Vegetarian BLT", "(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99);
addItem("BLT", "Bacon with lettuce & tomato on whole wheat", false, 2.99);
addItem("Soup of the day", "Soup of the day, with a side of potato salad", false, 3.29);
addItem("Hotdog", "A hot dog, with saurkraut, relish, onions, topped with cheese", false, 3.05);
}
public void addItem(String name, String description, boolean vegetarian, double price){
MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
if (numberOfItems >= MAX_ITEMS){
System.err.println("Sorry, menu is full! Can't add item to menu");
}else {
menuItems[numberOfItems] = menuItem;
numberOfItems += 1;
}
}
public Iterator createIterator(){
return new DinerMenuIterator(menuItems);
}
}
public class DinerMenuIterator implements Iterator {
MenuItem[] items;
int position = 0;
public DinerMenuIterator(MenuItem[] items){
this.items = items;
}
public Object next(){
MenuItem menuItem = items[position];
position += 1;
return menuItem;
}
@Override
public boolean hasNext() {
if (position >= items.length || items[position] == null) {
return false;
}else {
return true;
}
}
}
煎餅店的
public class PancakeHouseMenu {
ArrayList menuItems;
public PancakeHouseMenu(){
menuItems = new ArrayList();
addItem("K&B's Pancake Breakfast", "Pancakes with scrambled eggs, and toast", true,2.99);
addItem("Regular Pancake Breakfast", "Pancakes with fried eggs, sausage", false, 2.99);
addItem("Blueberry Pancakes", "Pancakes made with fresh blueberries", true, 3.49);
addItem("Waffles", "Waffles, with your choice of blueberries or strawberries", true, 3.59);
}
public void addItem(String name, String description, boolean vegetarian, double price){
MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
menuItems.add(menuItem);
}
public Iterator createIterator(){
return new PancakeIterator(menuItems);
}
}
public class PancakeIterator implements Iterator {
ArrayList menuItems;
int position = 0;
public PancakeIterator(ArrayList menuItems){
this.menuItems = menuItems;
}
public Object next(){
MenuItem menuItem =(MenuItem) menuItems.get(position);
position += 1;
return menuItem;
}
@Override
public boolean hasNext() {
if (position >= menuItems.size()){
return false;
}else {
return true;
}
}
}
這樣我們新建一個服務員,她就可以開始報菜名啦!
public class Waitress {
PancakeHouseMenu pancakeHouseMenu;
DinerMenu dinerMenu;
public Waitress(PancakeHouseMenu pancakeHouseMenu, DinerMenu dinerMenu){
this.pancakeHouseMenu = pancakeHouseMenu;
this.dinerMenu = dinerMenu;
}
public void printMenu(){
Iterator pancakeIterator = pancakeHouseMenu.createIterator();
Iterator dinerIterator = dinerMenu.createIterator();
System.out.println("MENU\n----\nBREAKFAST");
printMenu(pancakeIterator);
System.out.println("\nLUNCH");
printMenu(dinerIterator);
}
public void printMenu(Iterator iterator){
while (iterator.hasNext()){
MenuItem menuItem = (MenuItem)iterator.next();
System.out.print(menuItem.getName() + ", ");
System.out.print(menuItem.getPrice() + " -- ");
System.out.println(menuItem.getDescription());
}
}
}
測試一下
public class MenuTestDrive {
public static void main(String[] args) {
PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();
DinerMenu dinerMenu = new DinerMenu();
Waitress waitress = new Waitress(pancakeHouseMenu, dinerMenu);
waitress.printMenu();
}
}
我們看一下我們的實現關係圖
當然,java本身就提供了迭代器接口java.util.Iterator
迭代器模式提供一種方法順序訪問一個聚合對象中的各個元素,而又不暴露其內部的表示。
這個模式給你提供了一種方法,可以順序訪問一個聚集對象中的元素,而又不用知道內部是如何表示的。
如果你有一個統一的方法訪問聚合中的每一個對象,你就可以編寫多態的代碼和這些聚合搭配。另一個對你設計造成重要影響的,是迭代器模式把在元素之間遊走的責任交給迭代器,而不是聚合對象。
我們看一下該模式的類圖
迭代器意味着沒有次序。只是取出所有的元素,並不表示取出元素的先後就代表元素的大小次序。除非某個集合的文件有特別說明,否則不可以對迭代器所取出的元素大小順序作出假設。
外部迭代器,就是客戶通過調用next()取得下一個元素。迭代器的操作由客戶控制。
內部迭代器,是由迭代器自己控制。在這種情況下,因爲是由迭代器自行在元素之間遊走,所以你必須告訴迭代器在遊走過程中要做些什麼事,也就是說,你必須將操作傳入給迭代器。
組合模式
設計原則:一個類應該只有一個引起變化的原因。
類的每個責任都由改變的潛在區域。超過一個責任,意味着超過一個改變的區域。
內聚(cohesion),它用來度量一個類或模塊緊密地達到單一目的或責任。
當一個模塊或一個個類被設計成只支持一組相關的功能時,我們說它具有高內聚;反之,當被設計成支持一組不相關的功能時,我們說它具有低內聚。
新的需求:我們的兼併之路並沒有停止,我們又兼併了一個咖啡館,這樣我們可以按照之前的操作方法將它的菜單也統一管理起來。但是我們在新增咖啡館的菜單時,要修改服務員的代碼,並且相同的打印方法調用了多次;更嚴重的問題是,我們的餐廳菜單下有了一個甜點的子菜單。
聽起來好麻煩啊,我們用圖的形式來表述吧。
我們更加形象化一點,就可以得到一個樹形結構
組合模式允許你將對象組合成樹形結構來表現“整體/部分”層次結構。組合能讓客戶以一致的方式處理個別對象以及對象組合。
組合包含組件。組件有兩種:組合與葉節點元素。
我們看一下類圖
該模式是如何解決我們的問題?
那麼讓我們嘗試着解決現有問題吧
首先我們需要構建菜單組件
public abstract class MenuComponent {
public void add(MenuComponent menuComponent){
throw new UnsupportedOperationException();
}
public void remove(MenuComponent menuComponent){
throw new UnsupportedOperationException();
}
public MenuComponent getChild(int i){
throw new UnsupportedOperationException();
}
public String getName(){
throw new UnsupportedOperationException();
}
public String getDescription(){
throw new UnsupportedOperationException();
}
public double getPrice(){
throw new UnsupportedOperationException();
}
public boolean isVegetarian(){
throw new UnsupportedOperationException();
}
public void print(){
throw new UnsupportedOperationException();
}
public abstract Iterator createIterator();
}
然後實現具體組合和葉節點
菜單相當於組合
public class Menu extends MenuComponent {
ArrayList menuComponents = new ArrayList();
String name;
String description;
public Menu(String name, String description){
this.name = name;
this.description = description;
}
public void add(MenuComponent menuComponent){
menuComponents.add(menuComponent);
}
@Override
public void remove(MenuComponent menuComponent) {
menuComponents.remove(menuComponent);
}
@Override
public MenuComponent getChild(int i) {
return (MenuComponent)menuComponents.get(i);
}
@Override
public String getName() {
return name;
}
@Override
public String getDescription() {
return description;
}
@Override
public void print() {
System.out.print("\n" + getName());
System.out.println(", " + getDescription());
System.out.println("----------------");
Iterator iterator = menuComponents.iterator();
while (iterator.hasNext()){
MenuComponent menuComponent = (MenuComponent)iterator.next();
menuComponent.print();
}
}
public Iterator createIterator(){
return new CompositeIterator(menuComponents.iterator());
}
}
菜單子項相當於葉節點
public class MenuItem extends MenuComponent {
String name;
String description;
boolean vegetarian;
double price;
public MenuItem(String name, String description, boolean vegetarian, double price){
this.name = name;
this.description = description;
this.vegetarian = vegetarian;
this.price = price;
}
public String getName(){
return name;
}
public String getDescription(){
return description;
}
@Override
public double getPrice() {
return price;
}
@Override
public boolean isVegetarian() {
return vegetarian;
}
public void print(){
System.out.print(" " + getName());
if (isVegetarian()){
System.out.print("(v)");
}
System.out.println("," + getPrice());
System.out.println(" -- " + getDescription());
}
public Iterator createIterator(){
return new NullIterator();
}
}
然後我們實現一個服務員的代碼
public class Waitress {
MenuComponent allMenus;
public Waitress(MenuComponent allMenus){
this.allMenus = allMenus;
}
public void printMenu(){
allMenus.print();
}
public void printVegetarianMenu(){
Iterator iterator = allMenus.createIterator();
System.out.println("\nVEGETARIAN MENU\n-----");
while (iterator.hasNext()){
MenuComponent menuComponent = (MenuComponent)iterator.next();
try {
if (menuComponent.isVegetarian()){
menuComponent.print();
}
}catch (UnsupportedOperationException e){}
}
}
}
因爲我們需要尋找出菜單中的所有素食項,因此需要操作這棵樹的所有節點,並進行遍歷。這個時候就需要用到迭代器了。
我們實現一個組合迭代器
public class CompositeIterator implements Iterator {
Stack stack = new Stack();
public CompositeIterator(Iterator iterator){
stack.push(iterator);
}
public Object next(){
if (hasNext()){
// 注意這裏取的是棧的最上層迭代器,所以如果一個迭代器下還有迭代器的時候,優先取下層迭代器的值,然後再回到上層。
// 這纔是遞歸的關鍵所在。
Iterator iterator = (Iterator) stack.peek();
MenuComponent component = (MenuComponent) iterator.next();
if (component instanceof Menu){
stack.push(component.createIterator());
}
return component;
}else {
return null;
}
}
@Override
public boolean hasNext() {
if (stack.isEmpty()){
return false;
}else {
Iterator iterator = (Iterator) stack.peek();
if (!iterator.hasNext()){
stack.pop();
return hasNext();
}else {
return true;
}
}
}
public void remove(){
throw new UnsupportedOperationException();
}
}
一個空的迭代器
public class NullIterator implements Iterator {
public Object next(){
return null;
}
@Override
public boolean hasNext() {
return false;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
最後測試一下
public class MenuTestDrive {
public static void main(String[] args) {
MenuComponent pancakeHouseMenu = new Menu("PANCAKE HOUSE MENU", "Breakfast");
MenuComponent dinerMenu = new Menu("DINER MENU", "Lunch");
MenuComponent cafeMenu = new Menu("CAFE MENU", "Dinner");
MenuComponent dessertMenu = new Menu("DESSERT MENU", "Dessert of course!");
MenuComponent allMenus = new Menu("ALL MENUS", "All menus combined");
allMenus.add(pancakeHouseMenu);
allMenus.add(dinerMenu);
allMenus.add(cafeMenu);
pancakeHouseMenu.add(new MenuItem("K&B's Pancake Breakfast", "Pancakes with scrambled eggs, and toast", true,2.99));
pancakeHouseMenu.add(new MenuItem("Regular Pancake Breakfast", "Pancakes with fried eggs, sausage", false, 2.99));
pancakeHouseMenu.add(new MenuItem("Blueberry Pancakes", "Pancakes made with fresh blueberries", true, 3.49));
pancakeHouseMenu.add(new MenuItem("Waffles", "Waffles, with your choice of blueberries or strawberries", true, 3.59));
dinerMenu.add(new MenuItem("Vegetarian BLT", "(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99));
dinerMenu.add(new MenuItem("BLT", "Bacon with lettuce & tomato on whole wheat", false, 2.99));
dinerMenu.add(new MenuItem("Blueberry Pancakes", "Pancakes made with fresh blueberries", true, 3.49));
dinerMenu.add(new MenuItem("Waffles", "Waffles, with your choice of blueberries or strawberries", true, 3.59));
dinerMenu.add(new MenuItem("Pasta", "Spaghetti with Marinara Sauce, and a slice of sourdough bread", true, 3.89));
dinerMenu.add(dessertMenu);
dessertMenu.add(new MenuItem("Apple Pie", "Apple pie with a flakey crust, topped with vanilla ice cream", true, 1.59));
dessertMenu.add(new MenuItem("Cheesecake", "Creamy New York cheesecake, with a chocolate graham crust", true, 1.99));
cafeMenu.add(new MenuItem("Veggie Burger and Air Fries", "Veggie burger on a whole wheat bun, lettuce, tomato, and fries", true, 3.99));
cafeMenu.add(new MenuItem("Soup of the day", "A cup of the soup of the day, with a side salad", false, 3.69));
Waitress waitress = new Waitress(allMenus);
// waitress.printMenu();
waitress.printVegetarianMenu();
}
}
查看一下結果是否是我們想要的
組合模式以單一責任設計原則換取透明性。什麼是透明性?通過讓組件的接口同時包含一些管理子節點和葉節點的操作,客戶就可以將組合和葉節點一視同仁。也就是說,一個元素究竟是組合還是葉節點,對客戶是透明的。
在應用組合模式時,如果你有一個需要保持特定孩子次序的組合對象,就需要使用複雜的管理方案來進行孩子的增加和刪除(比如我們可以通過棧來做緩存),而且當你在這個層次結構內遊走時,應該要更加小心。
總結:我們在使用不同集合,但又需要統一管理這些集合的時候,就需要使用迭代器模式了,而且迭代器的實現還可以避免一些錯誤(關於remove操作導致的計數器問題)。
而當我們需要實現一種樹形結構進行管理的時候,就要立即想到組合模式了。文件管理系統就是最常見的樹形結構。