The observer pattern - design pattern

In the reality of development, many of the objects are not independent existence, which changes the behavior of an object may have led to one or more changes in the behavior of other objects also occur. This mode corresponds to the design - the observer pattern.

First, the definition of the pattern and characteristics

definition:

It refers to the presence of a plurality of objects-to-many dependencies, when a state of the object changes, all objects that depend on it have been notified and updated automatically. This mode is sometimes referred to publish - subscribe model, model - view mode, is the object behavioral patterns.

advantage:

  1. Reducing the coupling between the object and the observer, abstract coupling between the two.
  2. We have set up a trigger mechanism between the target and the observer.

Disadvantages:

  1. Dependence between the target and the observer is not completely removed, but also may appear circular references.
  2. While many observers target, conference notifications to spend a lot of time, reduce the efficiency of the program.

 

Second, the structure and mode of realization

Implement the observer pattern should be careful not to directly call between specific objectives and target specific viewers, or coupling between the two, in violation of the principles of design objects.

Structure Mode

The main role of the observer mode are as follows

  1. By all observers as well as abstract methods of target abstract class that provides aggregation and increase class object to hold the observer, the observer deleted object: abstract topics (subject) role.
  2. Specific topics: also known as class specific objectives to achieve the goals of the abstract method, when the specific subject of internal changes, notify all registered observers object.
  3. Abstract observer role: is an abstract class or interface, includes an updated his abstract method, when the change notification when I get specific theme is called.
  4. Specific observer role: Implement the abstract methods defined in the abstract observer.

Structure chart

 

According to the above configuration diagram of the code, the realization mode

Realization Mode

Abstract goal

abstract  class the Subject 
{ 
    protected List <the Observer> Observers = new new the ArrayList <the Observer> ();   
     // increase viewer method 
    public  void the Add (the Observer Observer) 
    { 
        observers.add (Observer); 
    }     
    // delete viewer method 
    public  void Remove (the observer observer) 
    { 
        observers.remove (observer); 
    }    
    public  abstract  void notifyObserver (); // notify the observer method 
}

specific goals

// specific target 
class ConcreteSubject the extends Subject 
{ 
    public  void notifyObserver () 
    { 
        System.out.println ( "Target changed ..." ); 
        System.out.println ( "----------- --- " );        
       
        for (Object OBS: Observers) 
        { 
            ((the Observer) OBS) .response (); 
        } 
       
    }           
}

Abstract observer

interface Observer
{
    void response(); //反应
}

Specific observer 1

class ConcreteObserver1 the implements the Observer 
{ 
    public  void Response () 
    { 
        System.out.println ( "specifically react observer 1!" ); 
    } 
}

Specific observer 2

class ConcreteObserver2 the implements the Observer 
{ 
    public  void Response () 
    { 
        System.out.println ( "specifically react observer 2!" ); 
    } 
}

Implementation

public class ObserverPattern
{
    public static void main(String[] args)
    {
        Subject subject=new ConcreteSubject();
        Observer obs1=new ConcreteObserver1();
        Observer obs2=new ConcreteObserver2();
        subject.add(obs1);
        subject.add(obs2);
        subject.notifyObserver();
    }
}

Program results are as follows:

Target changed ...
 -------------- 
specific observer 1 to react! 
2 to respond to specific viewer!

 

Scene Three application, mode

Through the analysis and application examples can be seen in front of the observer mode applies the following scenario?

  1. Many relationship exists an object, an object's state changes will affect other objects.
  2. When an abstract model has two aspects, one aspect of which is dependent on another aspect, these may be packaged in two separate objects so that they may be varied independently and reuse.

 

Extended four modes

4.1 observable class

observable target class is an abstract class, it has a vector vector, used to hold objects to notify all observers, including the three most important methods:

  1. void addObserver (Observer o) Methods: a viewer for adding a new object to the vector.
  2. void notifyObservers (Object arg) method: call update all observers object vector. The method of informing them that data changes. Usually the later addition of the first vector of the observer to be notified.
  3. void setChange () method: used to set a boolean internal flag, indicating the target object changes. When it is true, notifyObservers () will notify the viewer.

4.2 Observer Interface

Observer interface is an abstract viewer, which monitors changes in the target object when the target object is changed, the viewer is notified, and calls void update (Observable o, Object arg) method, the corresponding work.

 

4.3 Examples

Examples of the observer pattern achieved using crude Observable classes and Observer interface.

[Example 3] Using Observable Observer interface classes and the observer pattern instance crude oil futures.

Analysis: When crude oil prices, the short side sad, and more Fangju Xing; when oil prices fall, empty Fangju Xing, multi sad. Abstract goal in the present example (Observable) class defined in Java, a subclass can be defined directly, i.e., crude (OilFutures) class, which is a concrete target class, a class is defined SetPriCe (float price) method, when crude data call parent class changes notifyObservers (Object arg) to notify all observers; in the present example the abstract interface to the observer (observer) have been defined in Java, as long as the subclass is defined, i.e. the specific observation by category (including multi-party-based and space-based Bull Bear), and implement update (Observable o, Object arg) method may be. Figure 5 shows the structure of FIG.

Target categories: Crude oil futures

class OilFutures extends Observable
{
    private float price;   
    public float getPrice()
    {
        return this.price; 
    }
    public void setPrice(float price)
    {
        super.setChanged() ;  //设置内部标志位,注明数据发生变化 
        super.notifyObservers(price);    //通知观察者价格改变了 
        this.price=price ; 
    }
}

具体观察者类:多方

//具体观察者类:多方
class Bull implements Observer
{   
    public void update(Observable o,Object arg)
    {
        Float price=((Float)arg).floatValue();
        if(price>0)
        {
            System.out.println("油价上涨"+price+"元,多方高兴了!");
        }
        else
        {
            System.out.println("油价下跌"+(-price)+"元,多方伤心了!");
        }
    }
}

具体观察者类:空方

//具体观察者类:空方
class Bear implements Observer
{   
    public void update(Observable o,Object arg)
    {
        Float price=((Float)arg).floatValue();
        if(price>0)
        {
            System.out.println("油价上涨"+price+"元,空方伤心了!");
        }
        else
        {
            System.out.println("油价下跌"+(-price)+"元,空方高兴了!");
        }
    }
}

实现方式

public static void main(String[] args)
    {
        OilFutures oil=new OilFutures();
        Observer bull=new Bull(); //多方
        Observer bear=new Bear(); //空方
        oil.addObserver(bull);
        oil.addObserver(bear);
        oil.setPrice(10);
        oil.setPrice(-8);
    }

程序运行结果如下:

油价上涨10.0元,空方伤心了!
油价上涨10.0元,多方高兴了!
油价下跌8.0元,空方高兴了!
油价下跌8.0元,多方伤心了!

 

以上就是设计模式--观察者模式的基本讲解,希望对大家有所帮助!!!

Guess you like

Origin www.cnblogs.com/guohai-stronger/p/11831248.html