迭代器模式实验销售管理系统
时间: 2023-09-28 09:11:15 浏览: 50
迭代器模式是一种行为型设计模式,它提供一种访问聚合对象中各个元素的方法,而不需要暴露聚合对象的内部结构。在实验销售管理系统中,我们可以使用迭代器模式来访问产品列表中的各个产品,而不需要暴露产品列表的内部实现。
首先,我们需要定义一个产品类,它包含产品的名称、价格等基本信息。然后,我们定义一个产品列表类,它包含一个产品数组和相关的方法,如添加产品、获取产品数量等。在产品列表类中,我们实现一个迭代器接口,包含 hasNext() 和 next() 方法,用于遍历产品列表中的各个产品。
下面是一个简单的示例代码:
```java
// 产品类
public class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
// 产品列表类
public class ProductList implements Iterable<Product> {
private List<Product> products = new ArrayList<>();
public void addProduct(Product product) {
products.add(product);
}
public int getProductCount() {
return products.size();
}
public Product getProduct(int index) {
return products.get(index);
}
// 实现迭代器接口
public Iterator<Product> iterator() {
return new ProductIterator();
}
// 迭代器类
private class ProductIterator implements Iterator<Product> {
private int index = 0;
public boolean hasNext() {
return index < products.size();
}
public Product next() {
return products.get(index++);
}
}
}
// 测试代码
public class Test {
public static void main(String[] args) {
ProductList productList = new ProductList();
productList.addProduct(new Product("手机", 1999.0));
productList.addProduct(new Product("电脑", 4999.0));
productList.addProduct(new Product("平板", 2999.0));
// 使用迭代器遍历产品列表
for (Product product : productList) {
System.out.println(product.getName() + ": " + product.getPrice());
}
}
}
```
在上面的示例代码中,我们定义了一个 Product 类表示产品,一个 ProductList 类表示产品列表。ProductList 类实现了 Iterable 接口,包含一个迭代器类 ProductIterator,用于遍历产品列表中的各个产品。在测试代码中,我们使用迭代器遍历产品列表,并输出产品的名称和价格。
通过使用迭代器模式,我们可以在不暴露产品列表内部实现的情况下,访问产品列表中的各个产品。这样可以提高代码的灵活性和可维护性。