分类: 系统运维
2007-03-15 13:48:55
import java.util.*; import junit.framework.*; //访问者角色 interface Visitor { void visit(Gladiolus g); void visit(Runuculus r); void visit(Chrysanthemum c); } // The Flower hierarchy cannot be changed: //元素角色 interface Flower { void accept(Visitor v); } //以下三个具体元素角色 class Gladiolus implements Flower { public void accept(Visitor v) { v.visit(this);} } class Runuculus implements Flower { public void accept(Visitor v) { v.visit(this);} } class Chrysanthemum implements Flower { public void accept(Visitor v) { v.visit(this);} } // Add the ability to produce a string: //实现的具体访问者角色 class StringVal implements Visitor { String s; public String toString() { return s; } public void visit(Gladiolus g) { s = "Gladiolus"; } public void visit(Runuculus r) { s = "Runuculus"; } public void visit(Chrysanthemum c) { s = "Chrysanthemum"; } } // Add the ability to do "Bee" activities: //另一个具体访问者角色 class Bee implements Visitor { public void visit(Gladiolus g) { System.out.println("Bee and Gladiolus"); } public void visit(Runuculus r) { System.out.println("Bee and Runuculus"); } public void visit(Chrysanthemum c) { System.out.println("Bee and Chrysanthemum"); } } //这是一个对象生成器 //这不是一个完整的对象结构,这里仅仅是模拟对象结构中的元素 class FlowerGenerator { private static Random rand = new Random(); public static Flower newFlower() { switch(rand.nextInt(3)) { default: case 0: return new Gladiolus(); case 1: return new Runuculus(); case 2: return new Chrysanthemum(); } } } //客户测试程序 public class BeeAndFlowers extends TestCase { /* 在这里你能看到访问者模式执行的流程: 首先在客户端先获得一个具体的访问者角色 遍历对象结构 对每一个元素调用accept方法,将具体访问者角色传入 这样就完成了整个过程 */ //对象结构角色在这里才组装上 List flowers = new ArrayList(); public BeeAndFlowers() { for(int i = 0; i < 10; i++) flowers.add(FlowerGenerator.newFlower()); } Visitor sval ; public void test() { // It’s almost as if I had a function to // produce a Flower string representation: //这个地方你可以修改以便使用另外一个具体访问者角色 sval = new StringVal(); Iterator it = flowers.iterator(); while(it.hasNext()) { ((Flower)it.next()).accept(sval); System.out.println(sval); } } public static void main(String args[]) { junit.textui.TestRunner.run(BeeAndFlowers.class); } } |