访问者模式,表示一个作用于某对象结构中的各个元素的操作。它使你可以再不改变各元素的类的前提下定义作用于这些元素的新操作。
Visitor访问者模式定义作用于某个对象群中各个对象的操作. 它可以使你在不改变这些对象本身的情况下,定义作用于这些对象的新操作. --------------------------------------------------- package liu.visitor.demo;
public abstract class Action {//相当于visitor
//得到男人结论
public abstract void GetManconclusion(Man concreteElementA); //得到女人结论 public abstract void GetWomanconclusion(Woman concreteElementA); }
abstract class Person{
//接受 public abstract void Accept(Action visitor); } ------------------------------------------------------------ package liu.visitor.demo;
public class Success extends Action {
@Override
public void GetManconclusion(Man concreteElementA) { System.out.println(concreteElementA.getName()+"成功时,后面有个伟大的女人");
}
@Override
public void GetWomanconclusion(Woman concreteElementA) { System.out.println(concreteElementA.getName()+"成功背后多半有个不成功的男人");
}
}
------------------------------------------------------------ package liu.visitor.demo;
public class Failing extends Action {
@Override
public void GetManconclusion(Man concreteElementA) { System.out.println(concreteElementA.getName()+"失败时,闷头喝酒,谁都劝不住");
}
@Override
public void GetWomanconclusion(Woman concreteElementA) { System.out.println(concreteElementA.getName()+"失败时,泪眼汪汪,谁都劝不住");
}
}
------------------------------------------------------------ package liu.visitor.demo;
public class Man extends Person { private String name; public Man(String name){
------------------------------------------------------------ package liu.visitor.demo;
public class Woman extends Person {
private String name;
public Woman(String name){ this.setName(name); } @Override public void Accept(Action visitor) { visitor.GetWomanconclusion(this);
}
public void setName(String name) { this.name = name; } public String getName() { return name; }
}
------------------------------------------------------------ package liu.visitor.demo;
import java.util.ArrayList;
import java.util.List;
public class ObjectStructure {
private List<Person> elements = new ArrayList<Person>();
public void Attach(Person element){ elements.add(element); } public void Detach(Person element){ elements.remove(element); } public void Display(Action visitor){ for(Person e:elements){ e.Accept(visitor); } } } ------------------------------------------------------------ package liu.visitor.demo;
public class Main {
/**
* 访问者模式 */ public static void main(String[] args) { ObjectStructure o = new ObjectStructure(); o.Attach(new Man("man")); o.Attach(new Woman("woman")); Success s = new Success(); o.Display(s); Failing f = new Failing(); o.Display(f);
}
}
![]() |
设计模式之访问者模式,visitor
最新推荐文章于 2020-05-05 08:20:34 发布