您的位置:首页 > 其它

设计模式之观察者模式

2015-08-12 22:16 387 查看
设计模式之--观察者模式

1,定义:观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生改变时,会通知所有观察者对象,使他们能够自动更新自己。

2,“观察者模式”理解:当一个系统被分割成一系列相互协作的类时会有一个副作用,那就是必须维护与之相关的对象之间的一致性。开发人员并不希望为了保持这种一致性而导致个各类之间的紧密耦合,因为这样会给维护和扩展以及重用带来极大的不便。

而观察者模式就是解决这一问题的一个良好的解决方案,一个被观察者可以有任意数目的依赖于它的观察者,当被观察者的状态发生改变时,所有的观察者,当被观察者的状态发生改变时,所有的观察者都会收到通知。而被观察者在发出通知时也无需知道谁在观察自己,同时每一个观察者也并不知道其他的观察者的存在。

总而言之,使用观察者模式的最终结果就是接触耦合。让互相耦合的双方都依赖于抽象而不是具体。这样一来任何一方发生改变都不会影响到另一方。

3,适用情况:

1), 当一个抽象模型有两个方面,而其中一个方面必须依赖于另一个方面时;

2),当面对一个对象的改变需要同时改变其他的对象但是却不知道具体有多少个对象等待改变时;

3),当一个对象必须通知其他对象但是却不能与其他对象造成紧密耦合时;

4,代码:

主类:Main.class:

public class Main {

  public static void main(String[] args) {

    Spy spy007 = new Spy007();

    Country countryA = new CountryA("乙国",spy007);

    Country countryB = new CountryB("丙国",spy007);

    spy007.Attach(countryA);

    spy007.Attach(countryB);

    spy007.setIntelligence("甲国研制出了核武器!");

    spy007.Notify();

  }

}

抽象Country类:Country.class:

public abstract class Country {

  protected String countryName;

  protected Spy spy;

  public Country(String countryName,Spy spy) {

    this.countryName = countryName;

    this.spy = spy;

  }

   public abstract void Update();

}

抽象通知类:Spy.class:

​ ​import java.util.ArrayList;

​ ​public abstract class Spy {

​ ​   private ArrayList<Country> countrys = new ArrayList<Country>();

​ ​   private String intelligence;

​ ​   public String spyName;

​ ​

​ ​   public void Attach(Country country) {

​ ​     countrys.add(country);

​ ​   }

​ ​

​ ​   public void Detach(Country country) {

​ ​     countrys.remove(country);

​ ​   }

​ ​

​ ​   public void Notify() {

​ ​     for(int i=0;i<countrys.size();i++){

​ ​     ((Country)countrys.get(i)).Update();

​ ​   }

​ ​ }

​ ​

​ ​ public void setIntelligence(String intelligence){

​ ​   this.intelligence = intelligence;

​ ​ }

​ ​

​ ​ public String getIntelligence() {

​ ​   return intelligence;

​ ​ }

​ ​ ​ ​

​ ​}

​通知类:Spy007.class:

​ ​public class Spy007 extends Spy {

​ ​   public Spy007() {

​ ​     spyName = "007";

​ ​   }

​ ​}

​抽象Country实现类:CountryA.class:

​ ​public class CountryA extends Country {

​ ​

​ ​   public CountryA(String countryName, Spy spy) {

​ ​     super(countryName, spy);

​ ​   }

​ ​

​ ​   @Override

​ ​   public void Update() {

​ ​     System.out.println(countryName+"得到"+spy.spyName+"的情报"+spy.getIntelligence()+"决定与甲国建交");

​ ​   }

​ ​

​ ​}

​ ​抽象Country实现类:CountryB.class:

​ ​public class CountryB extends Country {

​ ​

​ ​   public CountryB(String countryName, Spy spy) {

​ ​     super(countryName, spy);

​ ​   }

​ ​

​ ​   @Override

​ ​   public void Update() {

​ ​     System.out.println(countryName+"得到"+spy.spyName+"的情报"+spy.getIntelligence()+"决定与甲国开战");

​ ​   }

​ ​

​ ​}

运行结果:



​ ​乙国得到007的情报甲国研制出了核武器!决定与甲国建交

​ ​丙国得到007的情报甲国研制出了核武器!决定与甲国建交
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: