interface Item { public void accept(Visitor visitor); public double getPrice(); } class Book(1) { private double price; public Book(double price) { (2); } public void accept(Visitor visitor) { //访问本元素 (3); } public double getPrice() { return price; } } //其它物品类略 interface Visitor { public void visit(Book book); //其它物品的visit方法 } class Cashier(4) { private double totalForCart; //访问Book类型对象的价格并累加 (5) { //假设Book类型的物品价格超过10元打8折 if(book.getPrice() < 10.0) { totalForCart += book.getPrice(); } else totalForCart += book.getPrice() * 0.8; } //其它visit方法和折扣策略类似,此处略 public double getTotal() { return totalForCart; } } class ShoppingCart { //normal shopping cart stuff private java.util.ArrayListitems = new java.util.ArrayList < > (); public double calculatePrice() { Cashier visitor = new Cashier(); for(Item item: items) { (6); } double total = visitor.getTotal(); return total; } public void add(Item e) { this.items.add(e); } }
请先在App中激活(应用市场搜“软考真题”)
2022-03-11
请先在App中激活(应用市场搜“软考真题”)
2022-05-25