读访问者模式资料:http://blog.csdn.net/chenssy/article/details/12029633
直觉这写法有问题。访问的应该是药单,而不是药,特改写如下:
public abstract class Visitor { protected String name; public void setName(String name) { this.name = name; } public abstract void visitor(Presciption p); }
public class Charger extends Visitor{ public void visitor(Presciption p) { for(Medicine m : p.list){ System.out.println("划价员:" + name + "给药" + m.getName() + "划价:" + m.getPrice()); } } }
public class WorkerOfPharmacy extends Visitor{ public void visitor(Presciption p) { for(Medicine m : p.list){ System.out.println("药房工作者:" + name + "拿药 :" + m.getName()); } } /*public void visitor(MedicineB b) { System.out.println("药房工作者:" + name + "拿药 :" + b.getName()); }*/ }
public class Medicine { protected String name; protected double price; public Medicine(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } //public abstract void accept(Visitor visitor); }
public class MedicineA extends Medicine{ public MedicineA(String name, double price) { super(name, price); } }
public class MedicineB extends Medicine { public MedicineB(String name, double price) { super(name, price); } }
public class Presciption { List<Medicine> list = new ArrayList<Medicine>(); public void accept(Visitor visitor){ visitor.visitor(this); } public void addMedicine(Medicine medicine){ list.add(medicine); } public void removeMedicien(Medicine medicine){ list.remove(medicine); } }
public class Client { public static void main(String[] args) { Medicine a = new MedicineA("板蓝根", 11.0); Medicine b = new MedicineB("感康", 14.3); Presciption presciption = new Presciption(); presciption.addMedicine(a); presciption.addMedicine(b); Visitor charger = new Charger(); charger.setName("张三"); Visitor workerOfPharmacy = new WorkerOfPharmacy(); workerOfPharmacy.setName("李四"); presciption.accept(charger); System.out.println("-------------------------------------"); presciption.accept(workerOfPharmacy); } }