观察者模式:
观察者模式打个比方就好比是好莱坞规则,好莱坞的规则就是你别通知我,我会通知你,在好莱坞有导演,有演员还有演员放到导演那的名片,那么有了片子以后,是导演拿到名片去通知每个演员,这个过程就是观察者模式,那么言归正传,在使用这个模式的时候我们一般会定义一个接口,那么这个接口就起到名片的作用,一个对象的操作可以触发多个对象的改变,姑且让该对象称作为A,其他对象为X,这些X对象实现上面所的接口,这些X对象重写这些接口,这样X对象就可以个干个的了,那么X对象们就相当于演员。可能有人要问 怎么去导演是怎么通知演员的那?是不是就在A里面逐个实例化X,这样的话就大错特错了,完全没有必要。我没只需要一个在整个系统中唯一的对象来管理这些X,换句话说可以在一个静态的对象里面注册这些X,这就相当于导演手中的名片夹嘿嘿嘿
package sa;
public class Director {
static CardCase cardCase = CardCase.initialize();
public static void main(String[] args) {
callActor();
cardCase.doSomeThing();
}
private static void callActor() {
Playactor1 playactor1 = new Playactor1();
Playactor2 playactor2 = new Playactor2();
cardCase.addActor(playactor1);
cardCase.addActor(playactor2);
}
}
package sa;
import java.util.HashSet;
import java.util.Set;
public class CardCase {
private static CardCase cardCase = new CardCase();
public CardCase(){
}
public static CardCase initialize(){
return cardCase;
}
private Set<Playactor> actorSet = new HashSet<Playactor>();
public void addActor(Playactor playactor){
actorSet.add(playactor);
}
public void removeActor(Playactor playactor){
actorSet.remove(playactor);
}
public void doSomeThing(){
for (Playactor actor : actorSet) {
actor.doSomeThing();
}
}
}
package sa;
public interface Playactor {
void doSomeThing();
}
package sa;
public class Playactor1 implements Playactor{
public void doSomeThing() {
System.err.println(">>>>>>>>>>Playactor1");
}
}
package sa;
public class Playactor2 implements Playactor {
public void doSomeThing() {
System.err.println(">>>>>>>>>>>>>>>Playactor2");
}
}