Observers (Subject /observers)

The so-called observer mode is only loosely coupled. For example, when data is updated, the changed() method is called to update state data, such as temperature, pressure, and so on. The problem with writing this way is that if you want to update more information, such as humidity, you have to change the code for the changed() method, which is the downside of tight coupling. For the Observer mode, we only need to maintain one Observable, that is, an Observable instance. When data changes, it only needs to maintain a set of observers. These observers implement the same interface. Notifying the Observer of which unified method needs to be invoked. The diagram below:

Publisher/Subscriber

In the publish-subscribe model, the publisher does not directly notify the subscriber, in other words, the publisher and the subscriber do not know each other. How do they communicate with each other? The answer is through third party triggering, that is, in the message queue, the publisher and the subscriber are contacted by the event name, and then the corresponding subscriber’s method is executed. As shown in figure:Unlike the observer model, in the publish-subscribe model, publishers and subscribers are not loosely coupled, but completely decoupled. Finally, a picture is attached to sum up:The observer pattern, only two characters — the observer and the observed and release in the subscription model, but it is not only the publisher and subscribers two roles, and a management and implement of message queue “Broker to Broker” and furthermore, the observer and the observed, is loosely coupled relationship between the publisher and subscribers, is completely no coupling

Redux observer mode

function createStore(reducer) { var state; var listeners = []; var getState = () => state; var dispatch = (action) => { state = reducer(state, action); listeners.forEach(l=>l()); } var subscribe = (listener) => { listeners.push(listener); return () => { listeners = listeners.filter((l) => l ! = listener) } } dispatch(); return { getState, dispatch, subscribe } } var reducer = (state = 0, action) => { if (! action) return state; console.log(action); switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } var store = createStore(reducer); store.subscribe(function () { document.querySelector('#counter').innerHTML = store.getState(); }); // The listener can get the current state from store.getState(). If React is used, this will trigger a rerendering of the View. // function listerner() { // let newState = store.getState(); // component.setState(newState); // } document.querySelector('#addBtn').addEventListener('click', function () { store.dispatch({type: 'INCREMENT'}); }); document.querySelector('#minusBtn').addEventListener('click', function () { store.dispatch({type: 'DECREMENT'}); });Copy the code