Home  >  Article  >  Backend Development  >  php design pattern (reprinted)

php design pattern (reprinted)

WBOY
WBOYOriginal
2016-07-30 13:30:50937browse

Original link: http://www.cnblogs.com/siqi/archive/2012/09/09/2667562.html

1. Singleton mode

As the name suggests, there is only one singleton mode Example. As an object creation mode, the singleton mode ensures that there is only one instance of a certain class, and it instantiates itself and provides this instance to the entire system.

There are three main points of the singleton pattern:

  1. First, a class can only have one instance;
  2. Second, it must create this instance by itself;
  3. Three, it must Provide this instance to the entire system yourself.

Why use PHP singleton mode

  1. 1. The application of php mainly lies in database application, There will be a large number of database operations in an application. When developing in an object-oriented way, if you use the singleton mode, you can avoid a large number of new operations consuming resources, and you can also reduce database connections so that too many connections are less likely to occur. .
  2. 2. If the system needs to have a class to globally control certain configuration information, Then it can be easily implemented using the singleton mode. For this, please refer to the FrontController part of zend Framework.
  3. 3. In one page request, facilitates debugging, Because all the code (such as database operation class db) is concentrated in one class, we can set hooks in the class and output logs to avoid var_dump and echo everywhere.

Example:

php design pattern (reprinted)

/**
* Singleton mode of design pattern
* $_instance must be declared as a static private variable
* The constructor must be declared as private to prevent external programs from new classes and thus lose the meaning of the singleton mode
* getInstance The () method must be set to public, and this method must be called to return a reference to the instance
* :: The operator can only access static variables and static functions
* new objects will consume memory
* Usage scenarios: The most commonly used places are Database Connectivity.
* After using the singleton pattern to generate an object, the object can be used by many other objects.
*/
class man
{
//Save the instance in this attribute private static $_instance;
//The constructor is declared as private, Prevent direct creation of objects private function __construct()
';
} //

Single case method public static function get_instance() (self::$_instance
));
                                                                   if(!isset(self::$_instance))                                                                          
return
self::$_instance; }                                                                     } function
test()
{         echo("test"); }
}
// This way of writing will go wrong because the constructor is declared as private//$test = new man;
//The following will get the Example class Singleton object
$test = man::get_instance();$test = man::get_instance();
$test
->test();// The copied object will Resulting in an E_USER_ERROR.
//$test_clone = clone $test;





2. Simple factory pattern

①Abstract base class: Define some abstract methods in the class, which are used to Implemented in subclasses
②Subclasses that inherit from abstract base classes: implement abstract methods in base classes
③Factory class: used to instantiate all corresponding subclasses

php design pattern (reprinted)

                                                                
classOperation{          //

Abstract method Cannot contain function body
                                                                                                                                     
/*
*         * Addition class                                                                          getValue($num1
,$num2){                                                                         +$num2; } } }/** * Subtraction class */ OperationSub
extends
Operation {
                                                                             
,$num2){                                                                                                                                                      
           * Multiplication class
                                                        operation
;                                                                                  Division class                                                                                                                                                                                                                         2
){                                                                                        num2 == 0) { Throw
exception ("The division cannot be 0"); catch (Exception
$e){                                                                                                                                                               } }


By using object-oriented inheritance features, we can easily extend the original program, such as: 'power', 'square root', 'logarithm', 'trigonometric function', 'statistics', etc. , to also avoid loading unnecessary code.

If we need to add a remainder class now, it will be very simple

We only need to write another class (this class inherits the virtual base class) and complete the corresponding functions in the class (for example: finding the power operation), and greatly reduces the degree of coupling, which is convenient for future maintenance and expansion

php design pattern (reprinted)

                                             class
OperationRem
extends
Operation {
                                                                                                                                                                                          %$num12
;                                                                
There is still an unresolved problem, which is how to let the program instantiate the corresponding object according to the operator input by the user? Solution: Use a separate class to implement the instantiation process. This class is the factory
/** * Engineering class, mainly used to create objects * Function: According to By inputting the operation symbols, the factory can instantiate the appropriate object
    ate
){

                                                                  (

$operate){php design pattern (reprinted)                                                                                                 break

;                                                                                                                                                                     .

                                                                                     
                                                                                   

                                                                                    break
; }

} }php design pattern (reprinted) $test

=Factory::createObj('/');

$result=$test
->getValue(23 ,0);

echo
$result;

Other notes about this mode:

Factory mode:
Take transportation as an example: Please be able to customize both the transportation and the production process of the transportation
1> Customize the transportation
1. Define an interface, which contains the methods of handover tools (start, run and stop)
2. Let airplanes, cars and other classes implement them
2> Customization factory (similar to above)
1. Definition An interface that contains the manufacturing method of delivery tools (start, run and stop)
2. Write factory classes for manufacturing aircraft and cars respectively to inherit and implement this interface

Original address: http://bbs.phpchina. com/thread-242243-1-1.html

3. Observer Pattern

The observer pattern is a behavioral pattern that defines a one-to-many dependency relationship between objects so that when the state of an object occurs When it changes, all objects that depend on it are notified and refreshed automatically. It perfectly separates the observer object and the observed object. A list of dependencies (observers) that are interested in the principal can be maintained in a separate object (the principal). Have all observers individually implement a common Observer interface to eliminate the direct dependency between the principal and dependent objects. (I can’t understand it anyway)

Used spl (standard php library)

php design pattern (reprinted)

class MyObserver1 implements SplObserver {
public function update(SplSubject $subject) {C
echo _______. '-'. $ SUBJECT- & GT; getName (); Tionp Update (splsubject $ $ Subject{) {

echo
______. '-'. $ SUBJECT- & GT; getName (); vate
$_observers; private $_name
; public function __construct($name
) {

$this->_observers = newSpl ObjectStorage();             
$this->_name = $name; }
public functionattach(SplObserver
$observer) { $this->_observers->attach($observer );
} public function
detach(SplObserver $observer) {                                                                        notify() {
       
foreach ( $this->_observers as $observer
) {                                          ​ public function
getName() {
return $this->_name; }}
$observer1 = newMyObserver1();

$observer2 = newMyObserver2();
$subject = new MySubject("test");$subject->attach($observer1);
$subject->attach($observer2);


$subject

->notify();

Reference original text: http://www.php.net/manual/zh/class.splsubject.php

4. Strategy mode

In this mode, algorithms are extracted from complex classes and can thus be easily replaced . For example, if you want to change the way pages are ranked in search engines, Strategy mode is a good choice. Think about the parts of a search engine ——One part traverses the pages, one part sorts each page, and the other part sorts based on the results of the arrangement. In complex examples, these parts are all in the same class. By using the Strategy pattern, you can put the arrangement part into another class to change the way the page is arranged without affecting the rest of the search engine's code.


As a simpler example, shown below is a User List class that provides a way to find a set of users based on a set of plug-and-play policies

php design pattern (reprinted)

//Define interface interface IStrategy {
    function filter($record);
}
//Implement interface method 1class FindAfterStrategy implements IStrategy {
private $_name;
public function __construct($name) {
$this->_name = $name;
}
public function filter($record ) {
                                                                                                                                                                                                class RandomStrategy implements IStrategy { public function
filter(
$record
) { return rand (0, 1) >= 0.5; } }//
Main class classUserList {private
$_list = array ();

public
function __construct($names) {if
($names != null) {                                                                                                                                                                                                                                                                       Add ($name
) { $this->_list [] = $name; } public
function find($filter) {                                                                                                                                                   ();
foreach ($this->_list as $user) {if
($filter->filter ($user))
                                                                                  
[] =
$user
;
array ( “Andy”, “Jack”, "Lori", "Megan" ) );
$f1 = $ul->find (
new
FindAfterStrategy ( "J" ) ) );
print_r ( $f1 ); $f2
= $ul->find ( new RandomStrategy () );
print_r (
$f2 );
Strategy pattern is very suitable for complex data management systems or data processing systems, both of which need to compare the way of data filtering, searching or processing. High flexibility The above introduces the PHP design pattern (reprinted), including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn