发帖    主题    评论    推荐    标签    作者    订阅    查搜    注册   登陆   关注
 
面向对象 设计模式 领域驱动设计 企业架构 框架 开发教程 微服务 CQRS 扩展性 并发编程 事件溯源 分布式 SOA

I'm a visitor, i would visit the ones i knew.

2003-01-10 17:39
赞助商链接

I'm learning Design Pattern, Here is what i think about the visitor Pattern. if something wrong, please inform me. thanks


//I'm a visitor, i could visit the ones i knew.
//if i want to visit a new one, i must know him, and he must accept me first.


//the following is Me -- a visitor, and i know He and She, they both accept me.
interface Visitor {
public void visit(He h);
// i know him
public void visit(She s);
// i know her
}

class He {
public void accept(Visitor me) {
// he accepts me
me.visit(this);
// so i could visit him
}
}
class She {
public void accept(Visitor me) {
// she accepts me 2
me.visit(this);
// so i could visit her
}
}


//and now if i want to visit It, i must know It, that is:
interface Visitor {
public void visit(He h);
// i know him
public void visit(She s);
// i know her

public void visit(It i);
// i must know it first
}

class It {
public void accept(Visitor me) {
// and it must accept me 2.
me.visit(this);
// so i could visit it.
}
}
// at this time, i could visit them separately

//if i want to visit them one by one, i must know all of them, and each of them must accept me. that is:
interface Acceptable {
public void accept(Visitor me);
}
// and each of them is acceptable, so :
class He implements Acceptalbe {
public void accept(Visitor me) {
// he accepts me
me.visit(this);
// so i could visit him
}
public void running() { }
}
class She implements Acceptalbe {
public void accept(Visitor me) {
// she accepts me 2
me.visit(this);
// so i could visit her
}
public void crying() { }
}
class It implements Acceptalbe {
public void accept(Visitor me) {
// and it also accept me.
me.visit(this);
// so i could visit it.
}
public void sleeping() { }
}


//now, i was visiting all the one i knows here:

class Visiting {
public static void main(String []args) {
Visitor me=new Visitor() {
// this is the real Me
public void visit(He h) {
// and i know all of them
h.runing();
}
public void visit(She s) {
s.crying();
}
public void visit(It i) {
i.sleeping();
}
};
Collection me=new LinkedList();
// now i'm ready to visit them
me.add(new He());
me.add(new She());
me.add(new It());

Iterator iter = me.iterator();
while ( iter.hasNext() ) {
// so i will visit them one by one.
Acceptable x=(Acceptable)iter.next();
x.accept(me);
// and they all accept me, so i could visit them successful them.
}

}
}

2003-01-13 14:23

我感觉没问题,good

赞助商链接

赞助商链接

返回顶部

移动版 关于本站 使用帮助 联系反馈 最佳分辨率1366x768
OpenSource JIVEJDON Powered by JdonFramework Code © 2002-20 jdon.com