Visitor 访问者模式适用的场景是,存在某个容器,里面的组成部分不会发生变化,对这些组成部分的访问,不是由这个容器决定,而是交给访问者决定。
举个生活中的例子,比如稻草人,卖包,卖鞋子这些固定的消费品,顾客有临时顾客和会员,会员有不同的等级,给的折扣也不同。
消费品抽象类:
public abstract class Consumption { abstract void cost(Member member); }
public class Bag extends Consumption{ private String name; private double price; public Bag(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public double getPrice() { return price; } @Override void cost(Member member) { member.pay(this); } }
鞋子:
public class Shoes extends Consumption{ private String name; private double price; public Shoes(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public double getPrice() { return price; } @Override void cost(Member member) { member.pay(this); } }
顾客:
public abstract class Member { abstract void pay(Bag bag); abstract void pay(Shoes shoes); }
金卡会员:
public class GoldMember extends Member{ @Override void pay(Bag bag) { System.out.println(bag.getName() + " cost " + bag.getPrice()*0.85); } @Override void pay(Shoes shoes) { System.out.println(shoes.getName() + " cost " + shoes.getPrice()*0.8); } }
银卡会员:
public class SilverMember extends Member{ @Override void pay(Bag bag) { System.out.println(bag.getName() + " cost " + bag.getPrice() * 0.95); } @Override void pay(Shoes shoes) { System.out.println(shoes.getName() + " cost " + shoes.getPrice()*0.9); } }
使用:
public class Store { public static void main(String[] args) { Bag b = new Bag("CK", 2000); Shoes ss = new Shoes("Red Dragonfly", 3000); Member goldMember = new GoldMember(); b.cost(goldMember); ss.cost(goldMember); Member silverMember = new SilverMember(); b.cost(silverMember); ss.cost(silverMember); } }