11.28
软件设计 石家庄铁道大学信息学院
实验 25:访问者模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解访问者模式的动机,掌握该模式的结构;
2、能够利用访问者模式法解决实际问题。
[实验任务一]:打包员
在我们课堂上的“购物车”的例子中,增加一个新的访问者:打包员,负责对购物车中货物装包。
实验要求:
1. 类图
2. 源代码
①、Porduct.java
package org.example.shiyanershiwu;
public interface Product {
void accept(Visitor visitor);
}
②、Apple.java
package org.example.shiyanershiwu;
public class Apple implements Product{
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
③、Book.java
package org.example.shiyanershiwu;
public class Book implements Product{
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
④、Visitor.java
package org.example.shiyanershiwu;
public abstract class Visitor {
protected String name;
public void setName(String name){
this.name = name;
}
public abstract void visit(Apple apple);
public abstract void visit(Book book);
}
⑤、Customer.java
package org.example.shiyanershiwu;
public class Customer extends Visitor {
@Override
public void visit(Apple apple) {
System.out.println("顾客" + name + "选苹果");
}
@Override
public void visit(Book book) {
System.out.println("顾客" + name + "买书");
}
}
⑥、Packer.java
package org.example.shiyanershiwu;
public class Packer extends Visitor {
@Override
public void visit(Apple apple) {
System.out.println("打包员" + name + "给苹果打包");
}
@Override
public void visit(Book book) {
System.out.println("打包员" + name + "给书打包");
}
}
⑦、Saler.java
package org.example.shiyanershiwu;
public class Saler extends Visitor {
@Override
public void visit(Apple apple) {
System.out.println("收银员" + name + "给苹果过秤,然后计算其价格");
}
@Override
public void visit(Book book) {
System.out.println("收银员" + name + "直接计算书的价格");
}
}
⑧、BuyBasket.java
package org.example.shiyanershiwu;
import java.util.ArrayList;
import java.util.List;
public class BuyBasket {
private List<Product> products=new ArrayList<>();
public void accept(Visitor visitor){
for(Product product:products){
product.accept(visitor);
}
}
public void addProduct(Product product){
products.add(product);
}
public void removeProduct(Product product){
products.remove(product);
}
}
⑨、Client.java
package org.example.shiyanershiwu;
public class Client {
public static void main(String[] args) {
BuyBasket buyBasket=new BuyBasket();
buyBasket.addProduct(new Apple());
buyBasket.addProduct(new Book());
Customer customer=new Customer();
customer.setName("张三");
buyBasket.accept(customer);
Saler saler=new Saler();
saler.setName("李四");
buyBasket.accept(saler);
Packer packer=new Packer();
packer.setName("王五");
buyBasket.accept(packer);
System.out.println("--------------------------------");
}
}
3. 运行结果