Head First Design Pattern - 2 - A Subject and Observer spar over the right way to get state information to the Observer

这实际上是对Observer模式中使用push方式还是pull方式的讨论,我从第一句话就开始笑个不停了,你要不要来试试看?

Subject: I'm glad we're finally getting a chance to chat in person.
Observer: Really? I thought you didn't care much about us Observers.
Subject: Well, I do my job, don't I? I always tell you what's going on... Just because I don't really know who you are doesn't mean I don't care. And besides, I do know the most important thing about you --- you implement the Observer interface.
Observer: Well yeah, but that's just a small part of who I am. Anyway, I know a lot more about you...
Subject: Oh yeah, like what?
Observer: Well, you're always passing your state around to us Observers so we can see what's goning on inside you. Which gets a little annoying at times...
Subject: Well excuuuse me. I have to send my state with my notifications so all you lazy Observers will know What happened!
Observer: Ok, wait just a minute here; first, we're not lazy, we just have other stuff to do in between your oh-so-important notifications, Mr. Subject, and second, why don't you let us come to you for the state we want rather than pushing it out to just everyone?
Subject: Well... I guess that might work. I'd have to open myself up even more though to let all you Observers come in and get the state that you need. That might be kind of dangerous. I can't let you come in and just snoop around looking at everything I've got.
Observer: Why don't you just write some public getter methods that will let us pull out the state we need?
Subject: Yes, I could let you pull my state. But won't that be less convenient for you? If you have to come to me every time you want something, you might have to make multiple method calls to get all the state you want. That's why I like push better... then you have everything you need in one notification.
Observer: Don't be so pushy! There's so many different kinds of us Observers, there's no way you can anticipate everything we need. Just let us come to you to get the state we need. That way, if some of us only need a little bit of state, we aren't forced to get it all. It also makes things easier to modify later. Say, for example, you expand yourself and add some more state, well if you use pull, you don't have to go around and change the update calls on every observer, you just need to change yourself to allow more getter methods to access you additional states.
Subject: Well, I can see the advantages to doing it both ways. I have noticed that there is a built-in Java Observer Pattern that allows you to use either push or pull.
Observer: Oh really? I think we're going to look at that next...
Subject: Great... maybe I'll get to see a good example of pull and change my mind.
Observer: What, us agree on something? I guess there's always hope

posted on 2006-04-06 17:03  Allen Young  阅读(345)  评论(0编辑  收藏  举报