大话设计模式_访问者模式
以男人女人不同的状态为例子.
package com.wzs.four;import java.util.ArrayList;import java.util.List;/** * 大话设计模式--page296 访问者模式 * * @author Administrator * */public class VisitorPattern {public static void main(String[] args) {ObjectStructure o = new ObjectStructure();o.attach(new Man("男人"));o.attach(new Woman("女人"));// 成功Success v1 = new Success("成功");o.display(v1);// 失败Failing v2 = new Failing("失败");o.display(v2);}}/* * 状态 */abstract class Action {public String actionFlag;public Action(String actionFlag) {this.actionFlag = actionFlag;}/* * 得到男人结论/反应 */public abstract void getManConclusion(Man concreteElementA);/* * 得到女人结论/反应 */public abstract void getWomanConclusion(Woman concreteElementB);}/* * 成功 */class Success extends Action {public Success(String actonFlag) {super(actonFlag);}@Overridepublic void getManConclusion(Man concreteElementA) {System.out.println(concreteElementA.name + " " + this.actionFlag + " 时,背后多半有一个伟大的女人.");}@Overridepublic void getWomanConclusion(Woman concreteElementB) {System.out.println(concreteElementB.name + " " + this.actionFlag + " 时,背后大多有一个不成功的男人.");}}/* * 失败 */class Failing extends Action {public Failing(String actionFlag) {super(actionFlag);}@Overridepublic void getManConclusion(Man concreteElementA) {System.out.println(concreteElementA.name + " " + this.actionFlag + " 时,闷头喝酒,谁也不用劝.");}@Overridepublic void getWomanConclusion(Woman concreteElementB) {System.out.println(concreteElementB.name + " " + this.actionFlag + " 时,眼泪汪汪,谁也劝不了.");}}/* * 人类 */abstract class Person {public String name;public Person(String name) {this.name = name;}/* * 接受 */public abstract void accept(Action visitor);}/* * 男人 */class Man extends Person {public Man(String name) {super(name);}@Overridepublic void accept(Action visitor) {visitor.getManConclusion(this);}}/* * 女人 */class Woman extends Person {public Woman(String name) {super(name);}@Overridepublic void accept(Action visitor) {visitor.getWomanConclusion(this);}}/* * 对象结构 */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);}}}