本文介绍23种设计模式之访问者模式。
定义
当你想要为一个对象的组合增加新的能力,且封装不重要时,就使用访问者模式。不清楚组合的可以看看JAVA设计模式之组合模式
描述
- 模式名称:VISITOR(访问者)
- 类型:对象行为型模式
- 意图:表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
- 适用性:
- 一个对象结构包含很多类对象,它们有不同的接口,而你想对这些对象实施一些依赖于其具体类的操作。
- 定义对象结构的类很少改变,但经常需要在此结构上定义新的操作。
- 效果:
- 优点:
- 访问者模式使得易于增加新的操作。
- 访问者集中相关的操作而分离无关的操作。
- 缺点:
- 增加新的组件类很困难。
- 破坏封装。访问者模式中具体元素对访问者公布细节,这破坏了对象的封装性。
类图
没有访问者时,在组合对象中增加功能
需要在树枝节点和叶子节点都要加入相应的功能
添加访问者
客户要求访问者从组合结构中获取信息,新的方法可以添加到访问者中,不会影响到组合。访问者可以调用get()方法获取每个元素的数据,这个就不用修改结构本身了
实现代码
Component
public abstract class Component {
abstract State getState();
public void add(Component component){
throw new UnsupportedOperationException();
}
public void remove(Component component){
throw new UnsupportedOperationException();
}
public Component getChild(int index){
throw new UnsupportedOperationException();
}
public String getName(){
throw new UnsupportedOperationException();
}
public String getDescription(){
throw new UnsupportedOperationException();
}
public Double getPrice(){
throw new UnsupportedOperationException();
}
public void print(){
throw new UnsupportedOperationException();
}
}
State
public class State {
private String healthRating;
private String carbs;
public String getCarbs() {
return carbs;
}
public void setCarbs(String carbs) {
this.carbs = carbs;
}
public String getHealthRating() {
return healthRating;
}
public void setHealthRating(String healthRating) {
this.healthRating = healthRating;
}
public State(String healthRating, String carbs) {
this.healthRating = healthRating;
this.carbs = carbs;
}
}
vistor
public class Visitor {
private Component component;
public Visitor(Component component){
this.component = component;
}
String getHealthRating(){
return component.getState().getHealthRating();
}
String getCarbs(){
return component.getState().getCarbs();
}
}