0%
访问者模式贯穿着Spark的底层源码
介绍
1 2
| 表示一个作用于某对象结构中的各元素的操作。 它使你可以在不改变各元素类的前提下定义作用于这些元素的新操作。
|
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
public interface Visitor { public void visit(Beijing beijing);
public void visit(Shanghai shanghai);
public void visit(Shenzhen shenzhen); }
public interface City { public void accept(Visitor visitor); }
public class Beijing implements City { @Override public void accept(Visitor visitor) { visitor.visit(this); } } public class Shanghai implements City { @Override public void accept(Visitor visitor) { visitor.visit(this); } } public class Shenzhen implements City { @Override public void accept(Visitor visitor) { visitor.visit(this); } }
public class TravelCities implements City { City[] cities;
public TravelCities() { cities = new City[]{new Beijing(), new Shanghai(), new Shenzhen()}; }
@Override public void accept(Visitor visitor) { for (int i = 0; i < cities.length; i++) { cities[i].accept(visitor); } } }
public class SingleVisitor implements Visitor { @Override public void visit(Beijing beijing) { System.out.println("bj"); }
@Override public void visit(Shanghai shanghai) { System.out.println("sh"); }
@Override public void visit(Shenzhen shenzhen) { System.out.println("sz"); } }
public class Demo { public static void main(String[] args) { TravelCities travelCities = new TravelCities(); travelCities.accept(new SingleVisitor()); } }
|