访问者模式

1. 访问者模式

访问者模式表示一个作用于某对象结构中的各元素的操作. 它使开发者可以在不改变各元素的类的前提下定义作用于这些元素的新操作

2. 超市中购物的列子

public interface Goods{
	double computer(Visitor visitor);
}

public class Wine implements Goods{
	public double accountByBottle(){
		return getCount()*getPrice();
	}
	public double computer(Visitor visitor){
		return visitor.computerMoney(this);
	}
	............
}

public class Television implements Goods{
	public double accountByNumber(){
		return getCount()*getNumber();
	}
	public double computer(Visitor visitor){
		return visitor.computerMoney(this);
	}
	............
}

3. 设计一个抽象的访问者类

public interface Visitor {
	double computerMoney(Wine wine);
	double computerMoney(Television television);
}




4. 设计一个具体的访问者类

public class VisitorImpl implements Vistor {
	public double computerMoney(Wine wine){
		return wine.accountByBottle();
	}
	public double computerMoney(Television television){
		return televison.accountByNumber();
	}
}



5. 购物车类

public class ShoppingCart{
	public void add(Object object){
		list.add(Object);
	}
	public void remove(Object object){
		list.remove(Object);
	}
	
	public List getList(){
		return list;
	}
	
	private List list = new ArrayList();
	
}


6. 计价器类

public class AccountMachine {
	private double total;
	public void account(List list){
		Visitor visitor = new VisitorImple();
		for (int i = 0; i < list.size(); i++){
			total+=(Goods)list.get(i).computer(visitor);
		}
		public double getTotal(){
			return total;
		}
	}
}


客户端调用代码

Wine wine = new Wine();
wine.setCount(10);
wine.setPrice(20f);
Television television = new Television();
television.setCount(12);
television.setPrice(1000f);

ShoppingCart shoppingCart = new ShoppingCart();
shoppingCart.add(wine);
shoppingCart.add(television);

AccountMachien accountMachine = new AccountMachine();
accountMachine.account(shoppingCart.getList());
account.getTotal();


你可能感兴趣的:(访问者模式)