This article mainly introduces a simple example of the observer pattern in php. The observer pattern is a common pattern in design patterns. , including two or more classes that interact with each other. This article directly gives the implementation code. Friends who need it can refer to it
The observer pattern is a common pattern in design patterns, including two or more classes that interact with each other. This mode allows a class to observe the state of another class. When the state of the observed class changes, the observer will be notified and update the corresponding state.
php's SPL standard class library provides the SplSubject and SplObserver interfaces for implementation. The observed class is called subject, and the class responsible for observation is called observer. This mode is that the SplSubject class maintains a specific state,
When this status changes, it will call the notify method. When calling the notify method, the update methods of all SplObserver instances previously registered using the attach method will be called. The Demo is as follows:
The code is as follows: