标签:
1 package headfirst.visitor; 2 3 abstract class Acceptor { 4 public abstract void accept(IVisitor visitor); 5 public abstract void execute()throws Exception; 6 } 7 8 class AcceptorInstance extends Acceptor{ 9 private IVisitor visitor; 10 11 @Override 12 public void accept(IVisitor visitor) { 13 this.visitor = visitor; 14 visitor.visit(this); 15 } 16 17 @Override 18 public void execute() throws Exception { 19 System.out.println(String.format("接受者:欢迎[%s]来做客!", visitor.getDescription())); 20 } 21 } 22 23 interface IVisitor{ 24 25 String getDescription(); 26 void visit(Acceptor acceptor); 27 28 } 29 30 class Visitor implements IVisitor{ 31 32 private final static String name = "jonex"; 33 34 @Override 35 public String getDescription() { 36 return name; 37 } 38 39 @Override 40 public void visit(Acceptor acceptor) { 41 try { 42 acceptor.execute(); 43 } catch (Exception e) { 44 e.printStackTrace(); 45 } 46 } 47 } 48 49 public class VisitorPattern{ 50 public static void main(String[] args) { 51 Acceptor acceptor = new AcceptorInstance(); 52 acceptor.accept(new Visitor()); 53 } 54 }
千里之行,始于足下。keep moving
-jonex
标签:
原文地址:http://www.cnblogs.com/jonex/p/4507537.html