在我们课堂上的“购物车”的例子中,增加一个新的访问者:打包员,负责对购物车中货物装包。
//Product.java package test25; public interface Product { void accept(Visitor visitor); } //Apple.java package test25; public class Apple implements Product { public void accept(Visitor visitor) { visitor.visit(this); } } //Book.java package test25; public class Book implements Product { public void accept(Visitor visitor) { visitor.visit(this); } } //BuyBasket.java package test25; import java.util.*; 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); } } //Customer.java package test25; public class Customer extends Visitor { public void visit(Apple apple) { System.out.println("顾客" + name + "选苹果。"); } public void visit(Book book) { System.out.println("顾客" + name + "买书。"); } } //Packer.java package test25; public class Packer extends Visitor { @Override public void visit(Apple apple) { // TODO 自动生成的方法存根 System.out.println("打包员" + name + "给购物车中的苹果打包。"); } @Override public void visit(Book book) { // TODO 自动生成的方法存根 System.out.println("打包员" + name + "给购物车中的书本打包。"); } } //Saler.java package test25; public class Saler extends Visitor { public void visit(Apple apple) { System.out.println("收银员" + name + "给苹果过秤,然后计算其价格。"); } public void visit(Book book) { System.out.println("收银员" + name + "直接计算书的价格。"); } } //Visitor.java package test25; 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); } //Client.java package test25; public class Client { public static void main(String[] args) { Product p1,p2; Visitor v1,v2,v3; p1=new Apple(); p2=new Book(); v1=new Saler(); v1.setName("张三"); v2=new Customer(); v2.setName("李四"); v3=new Packer(); v3.setName("王五"); BuyBasket basket = new BuyBasket(); basket.addProduct(p1); basket.addProduct(p2); basket.accept(v1); basket.accept(v2); basket.accept(v3); } }
标签:java,name,Visitor,void,visit,模式,public,访问者 From: https://www.cnblogs.com/qiuyutingyyds/p/17001604.html