Php design pattern Singleton pattern, factory pattern and observer pattern

Source: Internet
Author: User
Php design pattern Singleton pattern, factory pattern and observer pattern
This article introduces three modes in the php design mode: Singleton mode, Factory mode, and observer mode. For more information, see.

I,Singleton mode

Only one instance of this class exists in the application. For example, the singleton mode allows only one object to access the database, thus preventing multiple database connections from being opened.

A singleton class should include the following: Unlike a common class, a singleton class cannot be directly instantiated and can only be instantiated by itself. Therefore, to obtain such a restricted effect, the constructor must be marked as private. To make a singleton class effective without being directly instantiated, you must provide such an instance for it. Therefore, the singleton class must have a private static member variable that can save the class and a public static method that can access the instance.

In PHP, to prevent the singleton class object from being cloned to break the preceding implementation form of Singleton classes, an empty private _ clone () method is also provided for the basics.

A basic Singleton mode:

     

II,Factory modelFactory mode. you can create a class specifically used to implement and return instances of other classes based on input parameters or application configurations.

A basic factory model:

     

A factory that describes shape objects. it creates different shapes based on the number of input parameters.

     Width = $ width; $ this-> height = $ height;} public function getCircum () {return 2 * ($ this-> width + $ this-> height );} public function getArea () {return $ this-> width * $ this-> height;} // defines the circular class Circle implements IShape {private $ radii; public function _ construct ($ radii) {$ this-> radii = $ radii;} public function getCircum () {return 2 * M_PI * $ this-> radii ;} public function getArea () {return M_PI * pow ($ thi S-> radii, 2) ;}// create different shapes based on the number of input parameters. Class FactoryShape {public static function create () {switch (func_num_args () {case 1: return new Circle (func_get_arg (0); break; case 2: return new Rectangle (func_get_arg (0), func_get_arg (1); break ;}}// rectangular object $ c = FactoryShape: create (4, 2 ); var_dump ($ c-> getArea (); // circle object $ o = FactoryShape: create (2); var_dump ($ o-> getArea ();?>

Note: The Factory mode makes it easier to call a method because it only has one class and one method. if the factory mode is not used, it is necessary to decide which class and method should be called during the call; using the factory mode makes it easier to change the application in the future, such as adding a shape of support, you only need to modify the create () method in the factory class, instead of using the factory mode, you need to modify the code block that calls the shape.

3,Observer ModeThe Observer Mode provides another way to avoid close coupling between components. This mode is simple: an object becomes observability by adding a method (this method allows another object, that is, the Observer registers itself. When an observed object changes, the message is sent to the registered observer. The operations performed by these observers using this information are irrelevant to the observed objects. The result is that objects can communicate with each other without understanding the cause.

An example of a simple observer mode: when the listener is listening to the station (that is, joining a new listener), it sends a prompt message, the log observer who sends messages can observe these messages.

     Name ;}}// class Observable implements IObservable {protected $ observers = array (); public function addObserver ($ observer) {if (! ($ Observer instanceof IObserver) {return ;}$ this-> observers [] = $ observer;} public function removeObserver ($ observer_name) {foreach ($ this-> observers as $ index =>$ observer) {if ($ observer-> getName () ===$ observer_name) {array_splice ($ this-> observers, $ index, 1); return ;}}// simulate an observed class: radioStationclass RadioStation extends Observable {public function addListener ($ listener) {foreach ($ this-> observ Ers as $ observer) {$ observer-> onListen ($ this, $ listener );}}} // simulate an Observer class RadioStationLogger extends Observer {protected $ name = 'logger'; public function onListen ($ sender, $ args) {echo $ args, 'Join the radiostation. ';}} // simulate another Observer class OtherObserver extends Observer {protected $ name = 'other'; public function onListen ($ sender, $ args) {echo 'other observer .. ';}}$ rs = new RadioStation (); // inject observation By $ rs-> addObserver (new RadioStationLogger (); $ rs-> addObserver (new OtherObserver (); // remove the observer $ rs-> removeObserver ('other '); // you can see the observed information $ rs-> addListener ('CCTV ');?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.