visitor访问者模式

定义资源接口:

1 public interface Resource {
2     void accept(Visitor visitor);
3 }

 

定义visitor,支持2种类型,reader类资源和writer资源,访问writer资源需要额外一个line参数:

1 public interface Visitor {
2     void visit(Reader reader);
3 
4     void visit(Writer writer, String line);
5 }

 

1 public interface Reader {
2     String read();
3 }

 

 1 public class ReaderImpl implements Reader, Resource {
 2     @Override
 3     public String read() {
 4         return "Doc#1 factory riverwood staff manual.";
 5     }
 6 
 7     public void accept(Visitor visitor) {
 8         visitor.visit(this);
 9     }
10 }

 

 1 public class WriterImpl implements Writer, Resource {
 2 
 3     private String line;
 4     public WriterImpl(String line) {
 5         this.line = line;
 6     }
 7 
 8     @Override
 9     public int write(String line) {
10         return null == line ? 0 : line.length();
11     }
12 
13     @Override
14     public void accept(Visitor visitor) {
15         visitor.visit(this, line);
16     }
17 }

 

定义实际访问Resource的两个visitor角色:

 1 public class VipVisitorImpl implements Visitor {
 2 
 3     @Override
 4     public void visit(Reader reader) {
 5         String read = reader.read();
 6         System.out.println(read);
 7     }
 8 
 9     @Override
10     public void visit(Writer writer, String line) {
11         int write = writer.write(line);
12         if (write > 0) {
13             System.out.println("write success!");
14         }
15     }
16 }

 

 1 public class OrdinaryVisitorImpl implements Visitor {
 2 
 3     @Override
 4     public void visit(Reader reader) {
 5         String read = reader.read();
 6         System.out.println(read);
 7     }
 8 
 9     @Override
10     public void visit(Writer writer, String line) {
11         System.out.println("no access to writer!");
12     }
13 
14 }

 

调用:

 1 String line = "save this line";
 2         Resource reader = new ReaderImpl();
 3         Resource writer = new WriterImpl(line);
 4 
 5         Visitor ordinaryVisitor = new OrdinaryVisitorImpl();
 6         Visitor vipVisitor = new VipVisitorImpl();
 7 
 8         reader.accept(vipVisitor);
 9         reader.accept(ordinaryVisitor);
10 
11         writer.accept(vipVisitor);
12         writer.accept(ordinaryVisitor);

 

执行输出:

 

Doc#1 factory riverwood staff manual.

Doc#1 factory riverwood staff manual.

write success!

no access to writer!

 

posted @ 2020-09-25 15:43  Joynic  阅读(166)  评论(0编辑  收藏  举报