visitor访问者模式-创新互联
定义资源接口:
当前标题:visitor访问者模式-创新互联
本文链接:http://cdiso.cn/article/deedic.html
1 public interface Resource {
2 void accept(Visitor visitor);
3 }
定义visitor,支持2种类型,reader类资源和writer资源,访问writer资源需要额外一个line参数:
察哈尔右翼后网站制作公司哪家好,找成都创新互联公司!从网页设计、网站建设、微信开发、APP开发、响应式网站设计等网站项目制作,到程序开发,运营维护。成都创新互联公司自2013年创立以来到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选成都创新互联公司。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!
当前标题:visitor访问者模式-创新互联
本文链接:http://cdiso.cn/article/deedic.html