访问者模式是行为型模式的一种,通过访问者模式可以通过改变访问者改变元素的行为算法,比如目标对象中有两个元素A和B,可以传递不同的访问器达到从A到B访问或者从B到A访问。访问者模式的优点:
1)可以方便扩展不同的访问者改变对于对象的访问算法
2)符合单一职责,对类的访问独立出来
缺点:不符合迪米特法则
public interface Shop {
public void accept(Visitor visitor);
}
public class SugarShop implements Shop{
private String name;
private BigDecimal price;
public SugarShop(){}
public SugarShop(String name,BigDecimal price){
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
@Override
public void accept(Visitor visitor) {
visitor.visitor(this);
}
}
public interface Visitor {
public void visitor(SugarShop sugarShop);
}
public class NameVisitor implements Visitor{
@Override
public void visitor(SugarShop sugarShop) {
System.out.println(sugarShop.getName());
}
}
public class PriceVisitor implements Visitor{
@Override
public void visitor(SugarShop sugarShop) {
System.out.println(sugarShop.getPrice());
}
}
public class Client {
public static void main(String[] args) {
Visitor nameVisitor = new NameVisitor();
Visitor priceVisitor = new PriceVisitor();
Shop shop = new SugarShop("糖果",new BigDecimal("35"));
shop.accept(nameVisitor);
shop.accept(priceVisitor);
}
}