访问者模式
1、理解访问者模式的动机,掌握该模式的结构;
2、能够利用访问者模式法解决实际问题。
实验任务:打包员
在我们课堂上的“购物车”的例子中,增加一个新的访问者:打包员,负责对购物车中货物装包。
Client.java public class Client { public static void main(String[] args) { Product b1 = new Book(); Product a1 = new Apple(); Visitor visitor; BuyBasket basket = new BuyBasket(); basket.addProduct(b1); basket.addProduct(a1); visitor = new Customer(); visitor.setName("张三"); basket.accept(visitor); System.out.println("**************************************************"); visitor = new Packer(); visitor.setName("李四"); basket.accept(visitor); System.out.println("**************************************************"); visitor = new Saler(); visitor.setName("王五"); basket.accept(visitor); } } Customer.java 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 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 + "给书打包"); } } Product.java public interface Product { void accept(Visitor visitor); } Saler.java 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 + "计算书的价格"); } } Visitor.java 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); } Apple.java public class Apple implements Product{ @Override public void accept(Visitor visitor) { visitor.visit(this); } } Book.java public class Book implements Product{ @Override public void accept(Visitor visitor) { visitor.visit(this); } } BuyBasket.java 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); } }
标签:总结,java,name,visitor,每日,11.30,void,Visitor,public From: https://www.cnblogs.com/-GYP/p/17868480.html