场景
病人上医院都是先挂号、看病、医生写医药单。病人拿着医药单需要做两件事情
- 给收费处的收费员
- 给医药派药员
在此,需要你实现关于收费处收费员和派药员的场景
代码
public class Medicine {
private String name;
private long price;
private String address;
public Medicine() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public void accept(IVisitor visitor) {
visitor.visitor(this);
}
}
public class MedicineA extends Medicine {
public MedicineA() {
setName("板蓝根");
setPrice(1l);
setAddress("第一排第二格");
}
}
public class MedicineB extends Medicine {
public MedicineB() {
setName("感康");
setPrice(3l);
setAddress("第二排第二格");
}
}
public interface IVisitor {
public void visitor(Medicine medicine);
}
public class HospitalCashier implements IVisitor {
private String name;
public HospitalCashier(String name) {
this.name = name;
}
public void visitor(Medicine medicine) {
String msg = String.format("%s药需要%s元", medicine.getName(), medicine.getPrice());
System.out.println(msg);
}
}
public class MedicineTaker implements IVisitor {
private String name;
public MedicineTaker(String name) {
this.name = name;
}
public void visitor(Medicine medicine) {
System.out.println(String.format("%s药在%s", medicine.getName(), medicine.getAddress()));
}
}
public class Tester{
public static void main(String[] args) {
HospitalCashier cashier = new HospitalCashier("lining");
MedicineTaker taker = new MedicineTaker("zhanghai");
Medicine medicineA = new MedicineA();
Medicine medicineB = new MedicineB();
medicineA.accept(cashier);
medicineB.accept(cashier);
medicineA.accept(taker);
medicineA.accept(taker);
}
}
定义
表示一个作用于某对象结构中的各元素的操作。它使你可以在不该变各元素的类的前提下定义作用于这些元素的新操作。
类图
访问者.gif优缺点
优点
- 加visitor会容易,因为不用改变原有元素的内容
缺点 - 增加元素就比较不好搞,因为visitor的方法会变化
网友评论