软件设计 石家庄铁道大学信息学院
实验 25:访问者模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解访问者模式的动机,掌握该模式的结构;
2、能够利用访问者模式法解决实际问题。
[实验任务一]:打包员
在我们课堂上的“购物车”的例子中,增加一个新的访问者:打包员,负责对购物车中货物装包。
实验要求:
1. 提交源代码,不要提交类图;
package 模板方法模式;
public abstract class AbstractGoods implements Goods{
private String name;
private int num;
private int price;
public AbstractGoods(String name, int num,int price) {
this.name = name;
this.num = num;
this.price = price;
}
@Override
public abstract int accept(Visitor visitor);
public String getName() {
return name;
}
public int getNum() {
return num;
}
public int getPrice() {
return price;
}
}
package 模板方法模式;
public class Book extends AbstractGoods {
public Book(String name, int num, int price) {
super(name, num, price);
}
@Override
public int accept(Visitor visitor) {
return visitor.visit(this);
}
}
package 模板方法模式;
public class Client {
public static void main(String[] args) {
Shoppingcar shoppingCar = new Shoppingcar();
shoppingCar.add(new Book("鲁滨逊漂流记", 2, 25));
shoppingCar.add(new Book("活着", 2, 30));
shoppingCar.add(new Fruit("香蕉", 2, 5));
shoppingCar.add(new Fruit("火龙果", 6, 8));
shoppingCar.getCosts();
}
}
package 模板方法模式;
public class Fruit extends AbstractGoods {
public Fruit(String name, int num, int price) {
super(name, num, price);
}
@Override
public int accept(Visitor visitor) {
return visitor.visit(this);
}
}
package 模板方法模式;
public interface Goods {
public int accept(Visitor visitor);
public String getName();
public int getNum();
public int getPrice();
}
package 模板方法模式;
import java.util.ArrayList;
import java.util.List;
public class Shoppingcar {
private static final List<Goods> goods = new ArrayList<>();
private static final Visitor visitor = new shouyinyuan();
public void add(Goods g) {
goods.add(g);
}
public void remove(Goods g) {
goods.remove(g);
}
public int getCosts() {
int sum = 0;
int i = 1;
for (Goods g : goods) {
int c = g.accept(visitor);
System.out.println(g.getName() + ":" + c + "元");
sum = sum + c;
}
System.out.println("一共是:" + sum + " 元");
return sum;
}
}
package 模板方法模式;
public class shouyinyuan implements Visitor {
@Override
public int visit(Book book) {
int cost = book.getNum() * book.getPrice();
return cost;
}
@Override
public int visit(Fruit fruit) {
int cost = fruit.getNum() * fruit.getPrice();
return cost;
}
}
package 模板方法模式;
public interface Visitor {
int visit(Book book) ;
int visit(Fruit fruit);
}
2. 注意编程规范。