Php design mode

Source: Internet
Author: User
: This article mainly introduces the php design mode (reprinted). If you are interested in the PHP Tutorial, refer to it. Link: http://www.cnblogs.com/siqi/archive/2012/09/09/2667562.html

1. Singleton mode

The Singleton mode, as its name implies, has only one instance. As the object creation mode, the singleton mode ensures that a class has only one instance, and the instance is self-instantiated and provided to the entire system.

The Singleton mode has three main points:

  1. First, a class can only have one instance;
  2. Second, it must create the instance on its own;
  3. Third, it must provide the instance to the entire system.

Why use the PHP Singleton mode?

  1. 1. php applications mainly lie in database applications. a large number of database operations exist in an application. if you use the Singleton mode for object-oriented development, this can avoid the resource consumption of a large number of new operations, and reduce the number of database connections, which is not prone to too many ONS.
  2. 2. if you need a class in the system to globally control some configuration information, you can easily implement it using the Singleton mode. for details, refer to the FrontController section of zend Framework.
  3. 3. in a page request, debugging is easy, because all the code (such as database operation db) is concentrated in one class, we can set hooks in the class and output logs, this avoids var_dump and echo everywhere.

Example:

/**
* Singleton mode in design mode
* $ _ Instance must be declared as a static private variable
* The constructor must be declared as private to prevent external programs from losing the meaning of the Singleton mode due to new classes.
* The getInstance () method must be set to public. you must call this method to return a reference to the instance.
*: The operator can only access static variables and static functions.
* New objects consume memory.
* Use cases: database connections are the most common scenarios.
* After an object is generated in Singleton mode, the object can be used by many other objects.
*/
Class man
{
// Save the instance as private static $ _ instance in this attribute;
// The constructor is declared as private to prevent direct creation of the object private function _ construct ()
{
Echo 'I have been instantiated! ';
}
// Singleton method public static function get_instance ()
{
Var_dump (isset (self: $ _ instance ));

If (! Isset (self ::$ _ instance ))
{
Self: $ _ instance = new self ();
}
Return self: $ _ instance;
}
// Prevent the user from copying the object instance private function _ clone ()
{
Trigger_error ('Clone is not allow', E_USER_ERROR );
}
Function test ()
{
Echo ("test ");
}
}
// This write method will fail because the constructor is declared as private.
// $ Test = new man;
// The following Example object $ test = man: get_instance ();
$ Test = man: get_instance ();
$ Test-> test ();
// Copying an object will result in an E_USER_ERROR.
// $ Test_clone = clone $ test;

2. simple factory model

  • ① Abstract base class: Class defines abstract methods for implementation in sub-classes
  • ② Inherit from the subclass of the abstract base class: implement the abstract methods in the base class
  • ③ Factory class: Used to instantiate all corresponding subclasses



/**
*
* Define an abstract class so that the subclass can inherit and implement it.
*
*/
Abstract class Operation {
// The abstract method cannot contain the function body abstract public function getValue ($ num1, $ num2); // The subclass must implement this function}



/**
* Addition class
*/
Class OperationAdd extends Operation {
Public function getValue ($ num1, $ num2 ){
Return $ num1 + $ num2;
}
}
/**
* Subtraction class
*/
Class OperationSub extends Operation {
Public function getValue ($ num1, $ num2 ){
Return $ num1-$ num2;
}
}
/**
* Multiplication
*/
Class OperationMul extends Operation {
Public function getValue ($ num1, $ num2 ){
Return $ num1 * $ num2;
}
}
/**
* Division class
*/
Class OperationDiv extends Operation {
Public function getValue ($ num1, $ num2 ){
Try {
If ($ num2 = 0 ){
Throw new Exception ("The divisor cannot be 0 ");
} Else {
Return $ num1/$ num2;
}
} Catch (Exception $ e ){
Echo "error message:". $ e-> getMessage ();
}
}
}

By using the object-oriented inheritance feature, we can easily expand the original program, for example, 'multiplication fan', 'kaifang ', 'logarithm', and 'trigonometric function ', to avoid loading unnecessary code.

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

We only need to write another class (this class inherits the virtual base class) to complete the corresponding functions in the class (for example, evaluate the multiplication operator), and greatly reduce the coupling degree, convenience for future maintenance and expansion

/**
* Retrieve the remainder class (remainder)
*
*/
Class OperationRem extends Operation {
Public function getValue ($ num1, $ num2 ){
Return $ num1 % $ num12;
}
}

There is another unsolved problem: how can the program instantiate the corresponding object based on the operator entered by the user?
Solution: Use a separate class to implement the instantiation process. this class is the factory


/**
* Engineering, mainly used to create objects
* Function: the factory can create an appropriate object based on the input operator number.
*
*/
Class Factory {
Public static function createObj ($ operate ){
Switch ($ operate ){
Case '+ ':
Return new OperationAdd ();
Break;
Case '-':
Return new OperationSub ();
Break;
Case '*':
Return new OperationSub ();
Break;
Case '/':
Return new OperationDiv ();
Break;
}
}
}
$ Test = Factory: createObj ('/');
$ Result = $ test-> getValue (23, 0 );
Echo $ result;

Other notes about this mode:

Factory model:
Taking transportation as an example: you can customize both transportation and production processes.
1> custom transportation tools
1. define an interface that contains the method for handing over the tool (start and stop running)
2. Let airplanes and automobiles implement them.
2> custom factory (similar to above)
1. define an interface that contains the manufacturing method of the handed in tool (start and stop running)
2. write the aircraft separately, and the factory class of the automobile will inherit to implement this interface.

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

3. Observer Mode

The observer mode is a behavior mode that defines a one-to-many dependency between objects so that when the state of an object changes, all objects that depend on it are notified and automatically refreshed. It perfectly separates the observer object from the object to be observed. You can maintain a list of dependencies (observers) that interest the subject in an independent object (subject. Allow all observers to implement public Observer interfaces to cancel the direct dependency between the subject and the dependent object. (I cannot understand it anyway)

Spl (standard php library)

Class MyObserver1 implements SplObserver {
Public function update (SplSubject $ subject ){
Echo _ CLASS _. '-'. $ subject-> getName ();
}
}
Class MyObserver2 implements SplObserver {
Public function update (SplSubject $ subject ){
Echo _ CLASS _. '-'. $ subject-> getName ();
}
}
Class MySubject implements SplSubject {
Private $ _ observers;
Private $ _ name;
Public function _ construct ($ name ){
$ This-> _ observers = new SplObjectStorage ();
$ This-> _ name = $ name;
}
Public function attach (SplObserver $ observer ){
$ This-> _ observers-> attach ($ observer );
}
Public function detach (SplObserver $ observer ){
$ This-> _ observers-> detach ($ observer );
}
Public function required Y (){
Foreach ($ this-> _ observers as $ observer ){
$ Observer-> update ($ this );
}
}
Public function getName (){
Return $ this-> _ name;
}
}
$ Observer1 = new MyObserver1 ();
$ Observer2 = new MyObserver2 ();
$ Subject = new MySubject ("test ");
$ Subject-> attach ($ observer1 );
$ Subject-> attach ($ observer2 );

$ Subject-> publish Y ();

Http://www.php.net/manual/zh/class.splsubject.php ()

4. policy mode

In this mode, algorithms are extracted from complex classes and can be easily replaced. For example, if you want to change the page arrangement method in the search engine, the policy mode is a good choice. Think about the several parts of the search engine-one part traverses the page, the other part sorts each page, and the other part sorts the results based on the arrangement. In a complex example, these parts are in the same class. By using the policy mode, you can place the arranged parts into another class to change the page arrangement method without affecting the rest of the search engine code.


As a simple example, the following shows a user list class, which provides a method to find a group of users based on a set of plug-and-play policies.

// Define interface IStrategy {
Function filter ($ record );
}
// Implementation interface method 1 class FindAfterStrategy implements IStrategy {
Private $ _ name;
Public function _ construct ($ name ){
$ This-> _ name = $ name;
}
Public function filter ($ record ){
Return strcmp ($ this-> _ name, $ record) <= 0;
}
}
// Implementation interface method 1 class RandomStrategy implements IStrategy {
Public function filter ($ record ){
Return rand (0, 1) >=0.5;
}
}
// Main class UserList {
Private $ _ list = array ();
Public function _ construct ($ names ){
If ($ names! = Null ){
Foreach ($ names as $ name ){
$ This-> _ list [] = $ name;
}
}
}

Public function add ($ name ){
$ This-> _ list [] = $ name;
}

Public function find ($ filter ){
$ Recs = array ();
Foreach ($ this-> _ list as $ user ){
If ($ filter-> filter ($ user ))
$ Recs [] = $ user;
}
Return $ recs;
}
}
$ Ul = new UserList (array (
"Andy ",
"Jack ",
"Lori ",
"Megan"
));
$ F1 = $ ul-> find (new FindAfterStrategy ("J "));
Print_r ($ f1 );
$ F2 = $ ul-> find (new RandomStrategy ());

Print_r ($ f2 );

The rule mode is very suitable for complex data management systems or data processing systems. The two require high flexibility in data filtering, search, or processing methods.

The above introduces the php design mode (reprinted), including the content, and hope to be helpful to friends who are interested in the PHP Tutorial.

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.