Java实现访问者模式的购物车实例
package Lab25_Visitor;
import java.util.ArrayList;
import java.util.Iterator;
public class Buychart {
public static 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);
}
public static class Customer extends Visitor { // 顾客访者类 继承了访问者抽象类
public void visit(Apple apple) {
System.out.println("顾客" + name + "选苹果。");
}
public void visit(Book book) {
System.out.println("顾客" + name + "买书。");
}
}
public static class Packer extends Visitor { // 打包员类 继承了访问者抽象类
public void visit(Apple apple) {
System.out.println("打包员" + name + "打包苹果。");
}
public void visit(Book book) {
System.out.println("打包员" + name + "打包书。");
}
}
public static class Saler extends Visitor {
public void visit(Apple apple) {
System.out.println("收银员" + name + "给苹果过秤,然后计算其价格。");
}
public void visit(Book book) {
System.out.println("收银员" + name + "直接计算书的价格。");
}
}
public static 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);
}
}
public interface Product { // 产品接口
void accept(Visitor visitor);
}
public static class Apple implements Product { // 苹果类实现产品接口
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
public static class Book implements Product { // 书类实现产品接口
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
public static void main(String a[]) {
Product b1 = new Book();
Product b2 = new Book();
Product a1 = new Apple();
Visitor visitor;
Visitor visitor1;
Visitor visitor2;
BuyBasket basket = new BuyBasket();
basket.addProduct(b1);
basket.addProduct(b2);
basket.addProduct(a1);
visitor = new Customer();
visitor1 = new Packer();
visitor2 = new Saler();
visitor.setName("张三");
visitor1.setName("李四");
visitor2.setName("王五");
basket.accept(visitor);
basket.accept(visitor1);
basket.accept(visitor2);
}
}