具体代码
//Visitor.java
package org.example.test023;
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.test023;
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 + "买书");
}
}
//Saler.java
package org.example.test023;
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 + "直接计算书的价格");
}
}
//Packager.java
package org.example.test023;
public class Packager extends Visitor {
@Override
public void visit(Apple apple) {
System.out.println("打包员" + name + "给苹果打包");
}
@Override
public void visit(Book book) {
System.out.println("打包员" + name + "给书籍打包");
}
}
//Product.java
package org.example.test023;
public interface Product {
void accept(Visitor visitor);
}
//Apple.java
package org.example.test023;
public class Apple implements Product {
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
//Book.java
package org.example.test023;
public class Book implements Product {
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
//BuyBasket.java
package org.example.test023;
import java.util.ArrayList;
import java.util.Iterator;
public class BuyBasket {
private ArrayList list = new ArrayList();
public void accept(Visitor visitor) {
Iterator i = list.iterator();
while (i.hasNext()) {
((Product)i.next()).accept(visitor);
}
}
//加入购物车
public void addProduct(Product product) {
list.add(product);
}
//移出购物车
public void removeProduct(Product product) {
list.remove(product);
}
}
//Client.java
package org.example.test023;
public class Client {
public static void main(String[] args) {
Product b1 = new Book();
Product b2 = new Book();
Product b3 = new Apple();
Visitor visitor;
BuyBasket buyBasket = new BuyBasket();
buyBasket.addProduct(b1);
buyBasket.addProduct(b2);
buyBasket.addProduct(b3);
//设置顾客为张三
visitor = new Customer();
visitor.setName("张三");
buyBasket.accept(visitor);
//设置收银员为李四
visitor = new Saler();
visitor.setName("李四");
buyBasket.accept(visitor);
//设置打包员为王五
visitor = new Packager();
visitor.setName("王五");
buyBasket.accept(visitor);
}
}
运行结果