设计模式之九:迭代器与组合模式

有许多方法可以把对象堆起来成为一个集合(Collection),比如放入数组、堆栈或散列表中。若用户直接从这些数据结构中取出对象,则需要知道具体是存在什么数据结构中(如栈就用peek,数组[])。迭代器能够让客户遍历你的对象而又无法窥视你存储对象的方式。

对象村餐厅和煎饼屋合并了,它们有着不同的菜单列表,但菜单项基础都是一样的。

class MenuItem
{
private:string name;string description;bool vegetarian;double price;public:MenuItem(string name, string description, bool vegetarian, double price){this->name = name;this->description = description;this->vegetarian = vegetarian;this->price = price;}string getName(){return name;}string getDescription(){return description;}bool isVegetarian(){return vegetarian;}double getpPrice(){return price;}
};

下面就写Java代码了,改成C++一时半会还是做不过来。

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);}public void addItem(String name, String description, boolean vegetarian, double price){MenuItem menuItem = new MenuItem(name, description, vegetarian, price);menuItems.add(menuItem);}public ArrayList getMenuItems(){return menuItems;}
};/ ********************************************************/
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", true, 2.99);}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;}}public MenuItem[] getMenuItems(){return menuItems;}
};

这两种不同的菜单表现方式,会使得女招待需要知道菜单的实现细节,才能对菜单进行遍历。

PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();
ArrayList breakfastItems = pancakeHouseMenu.getMenuItems();for breakfastItems.size()
MenuItem menuItem = (MenuItem)breakfastItems.get(i);/ ******************************************************************* /
DinerMenu dinerMenu = new DinerMenu();
MenuItem[] lunchItems = DinerMenu.getMenuItems();for lunchItems.size()
MenuItem menuItem = lunchItems[i];

如果还有第三家餐厅以不同的实现出现,我们就需要有三个循环。

因此,我们需要创建一个对象(迭代器),封装“遍历集合内的每个对象的过程”。

Iterator iter = breakfastItems.createIterator();while (iter.hasNext())
{MenuItem menuItem = (MenuItem)iter.next();
}

 当我们拥有迭代器接口后,我们就可以为各种对象集合实现迭代器

public interface Iterator
{boolean hasNext();Object next();
};public class DinerMenuIterator implements Iterator
{MenuItem[] items;int position = 0;public DinerMenuIterator(MenuItem[] items){this.items = items;}public Object next(){MenuItem menuItem = items[position++];return menuItem;}public boolean hasNext(){if (position >= items.length || items[position] == null) return false;else return true;}
};

有了DinerMenuIterator后就可以改造DinerMenu和PancakeHouseMenu。

public class DinerMenu
{static final int MAX_ITEMS = 6;int numberOfItems = 0;MenuItem[] menuItems;// public DinerMenu()// addItem()// 删除getMenuItems()public Iterator createIterator(){// 返回迭代器接口。客户不需要知道餐厅菜单如何维护菜单项return new DinerMenuIterator(menuItems);}
};
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);}private void printMenu(Iterator iterator) {while (iterator.hasNext()) {MenuItem menuItem = iterator.next();System.out.print(menuItem.getName() + ", ");System.out.print(menuItem.getPrice() + " -- ");System.out.println(menuItem.getDescription());}}
}

现在可以进一步对waitress进行优化,因为她还捆绑与两个具体的菜单类。但在优化之前,我们先看下目前的设计。

 除了使用自己构建的迭代器接口外,还可以直接使用java.util的迭代器接口,同时ArrayList也有一个返回迭代器的方法。

 

// 煎饼屋的代码public Iterator createIterator()
{return menuItems.iterator();
}// 餐厅的代码public class DinerMenuIterator implements Iterator {MenuItem[] list;int position = 0;public DinerMenuIterator(MenuItem[] list) {this.list = list;}public MenuItem next() {MenuItem menuItem = list[position];position = position + 1;return menuItem;}public boolean hasNext() {if (position >= list.length || list[position] == null) {return false;} else {return true;}}public void remove() {if (position <= 0) {throw new IllegalStateException("You can't remove an item until you've done at least one next()");}if (list[position-1] != null) {for (int i = position-1; i < (list.length-1); i++) {list[i] = list[i+1];}list[list.length-1] = null;}}}

最后我们再给菜单一个共同的接口,然后修改下女招待。

public interface Menu
{public Iterator createIterator();
}public class Waitress {Menu pancakeHouseMenu;Menu dinerMenu;public Waitress(Menu pancakeHouseMenu, Menu dinerMenu) {this.pancakeHouseMenu = pancakeHouseMenu;this.dinerMenu = dinerMenu;}public void printMenu() {Iterator<MenuItem> pancakeIterator = pancakeHouseMenu.createIterator();Iterator<MenuItem> dinerIterator = dinerMenu.createIterator();System.out.println("MENU\n----\nBREAKFAST");printMenu(pancakeIterator);System.out.println("\nLUNCH");printMenu(dinerIterator);}private 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());}}}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/66082.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ES主集群的优化参考点

因为流量比较大&#xff0c; 导致ES线程数飙高&#xff0c;cpu直往上窜&#xff0c;查询耗时增加&#xff0c;并传导给所有调用方&#xff0c;导致更大范围的延时。如何解决这个问题呢&#xff1f; ES负载不合理&#xff0c;热点问题严重。ES主集群一共有几十个节点&#xff0…

yolov5的pytorch配置

1. conda create -n rdd38 python3.82、pip install torch1.8.0 torchvision0.9.0 torchaudio0.8.0 -f https://download.pytorch.org/whl/cu113/torch_stable.html -i https://pypi.tuna.tsinghua.edu.cn/simple 3、conda install cudatoolkit10.2

IC 的资源体系

信息共享空间是集信息资源、各类软硬件设施于一体的一个综合性动态服务模 式&#xff0c;其最大特点是资源共享。因此&#xff0c;要加强电脑终端、打印机等硬件设施的建设&#xff0c; 同时强调文献数据库、电子图书、学位论文、各类免费软件等信息资源的建设&#xff0c;提…

2023年03月 C/C++(六级)真题解析#中国电子学会#全国青少年软件编程等级考试

C/C++编程(1~8级)全部真题・点这里 第1题:波兰表达式 波兰表达式是一种把运算符前置的算术表达式,例如普通的表达式2 + 3的波兰表示法为+ 2 3。波兰表达式的优点是运算符之间不必有优先级关系,也不必用括号改变运算次序,例如(2 + 3) * 4的波兰表示法为* + 2 3 4。本题求解…

Ansible自动化运维工具(二)

目录 &#xff08;6&#xff09;copy模块 &#xff08;7&#xff09;file模块 ​编辑​编辑&#xff08;8&#xff09;hostname模块 &#xff08;9&#xff09;ping模块 &#xff08;10&#xff09;yum 模块 &#xff08;11&#xff09;service/system模块 ​编辑 ​…

机器学习笔记之最优化理论与方法(五)凸优化问题(上)

机器学习笔记之最优化理论与方法——凸优化问题[上] 引言凸优化问题的基本定义凸优化定义&#xff1a;示例 凸优化与非凸优化问题的区分局部最优解即全局最优解凸优化问题的最优性条件几种特殊凸问题的最优性条件无约束凸优化等式约束凸优化非负约束凸优化 引言 本节将介绍凸优…

windows11 利用vmware17 安装rocky9操作系统

下载相关软件和镜像 vmware17 下载 下载页面 Download VMware Workstation Pro ​ rocky8镜像下载 官网链接&#xff1a;Rocky Linux 下载页面 Download Rocky | Rocky Linux 点击Minimal下载 安装rocky9 选择镜像文件&#xff0c;点击下一步 点击下一步 启动虚拟机 选…

网络环境下促进有效学习发生的策略

1.构建良好的网络学习环境 学习者在网络中的学习&#xff0c;必须在一定的、适合学习的环境中进行&#xff0c;构建和谐和 宽松的学习环境是激发学习者有效学习的前提。在这样的环境中&#xff0c;应该有学习者学 习所需要的一些网络资源&#xff0c;如各种教学网站&#xf…

C++面试题(期)-数据库(二)

目录 1.3 事务 1.3.1 说一说你对数据库事务的了解 1.3.2 事务有哪几种类型&#xff0c;它们之间有什么区别&#xff1f; 1.3.3 MySQL的ACID特性分别是怎么实现的&#xff1f; 1.3.4 谈谈MySQL的事务隔离级别 1.3.5 MySQL的事务隔离级别是怎么实现的&#xff1f; 1.3.6 事…

Windows和Linux环境中安装Zookeeper具体操作

1.Windows环境中安装Zookeeper 1.1 下载Zookeeper安装包 ZooKeeper官网下载地址 建议下载稳定版本的 下载后进行解压后得到如下文件&#xff1a; 1.2 修改本地配置文件 进入解压后的目录&#xff0c;将zoo_example.cfg复制一份并重命名为zoo.cfg,如图所示&#xff1a; 打…

uniapp 微信小程序添加隐私保护指引

隐私弹窗&#xff1a; <uni-popup ref"popup"><view class"popupWrap"><view class"popupTxt">在你使用【最美万年历】之前&#xff0c;请仔细阅读<text class"blueColor" click"handleOpenPrivacyContract…

ElasticSearch学习5-- 使用RestClient查询文档

1、查询基本步骤 1、创建SearchRequest对象 2、准备Request.source()&#xff0c;也就是DSL。 QueryBuilders来构建查询条件 传入Request.source() 的 query() 方法 3、发送请求&#xff0c;得到结果 4、解析结果&#xff08;参考JSON结果&#xff0c;从外到内…

国标视频融合云平台EasyCVR视频汇聚平台关于远程控制的详细介绍

EasyCVR国标视频融合云平台是一个能在复杂网络环境下统一汇聚、整合和集中管理各类分散视频资源的平台。该平台提供了多种视频能力和服务&#xff0c;包括视频监控直播、云端录像、云存储、录像检索与回看、智能告警、平台级联、集群、电子地图、H.265视频自动转码和智能分析等…

几种Go版本管理工具

缘起: 编译下面这段代码时,在Mac上没有什么问题,正常运行, 点击查看代码: package mainimport ( "bytes" "encoding/binary" "encoding/json" "fmt" "log" "math/rand" "net/http" "time")fu…

C++包含整数各位重组

void 包含整数各位重组() {//缘由https://bbs.csdn.net/topics/395402016int shu 100000, bs 4, bi shu * bs, a 0, p 0, d 0;while (shu < 500000)if (a<6 && (p to_string(shu).find(to_string(bi)[a], p)) ! string::npos && (d to_string(bi…

C++ 获取进程信息

1. 概要 通常对于一个正在执行的进程而言&#xff0c;我们会关注进程的内存/CPU占用&#xff0c;网络连接&#xff0c;启动参数&#xff0c;映像路径&#xff0c;线程&#xff0c;堆栈等信息。 而通过类似任务管理器&#xff0c;命令行等方式可以轻松获取到这些信息。但是&…

实现一个简单的控制台版用户登陆程序, 程序启动提示用户输入用户名密码. 如果用户名密码出错, 使用自定义异常的方式来处理

//密码错误异常类 public class PasswordError extends Exception {public PasswordError(String message){super(message);} }//用户名错误异常类 public class UserError extends Exception{public UserError(String message){super(message);} }import java.util.Scanner;pu…

Vue之html中特殊符号的展示

Vue之html中特殊符号的展示 在html中使用特殊字符时直接展示会报错&#xff0c;需要使用实体名称或者实体编号才能展示。 最常用的字符实体 显示结果 描述 实体名称 实体编号空格 < 小于号 < &…

代码随想录 - Day32 - 回溯:组合问题

代码随想录 - Day32 - 回溯&#xff1a;组合问题 39. 组合总和 做题的时候遇到一点疑问&#xff1a; 为什么必须是result.append(path[:])而不能写成result.append(path)呢&#xff1f; 原因&#xff1a; result.append(path)往result中添加的是path这个参数&#xff0c;后续…

java内存溢出问题分析记录

最好找到必现流程在idea-VMOption中输入参数&#xff1a; -XX:HeapDumpOnOutOfMemoryError将会在内存溢出发生时&#xff0c;在项目根目录生成dump文件。 打开jdk自带的分析工具java visualVM&#xff0c;可以打开该文件&#xff0c;定位到内存溢出发生的代码位置。 分析该位…