PHP patterns (factory & Singleton)

Source: Internet
Author: User
Factory

Definition:

<? PHP  Class  Example {  //  The factory Method      Public   Static   Function Factory ( $ Type  ){  If ( Include_once 'Drivers /'. $ Type . '. Php' ){ $ Classname = 'Driver _'. $ Type  ;  Return   New   $ Classname  ;}  Else  {  Throw   New   Exception ('Driver not found' );}}} ?>

Usage:

<?PHP//Load a MySQL driver$ Mysql= Example: Factory ('mysql');//Load a SQLite driver$ SQLite= Example: Factory ('sqlite');?>

 

 

Singleton

Definition:

<? PHP  Class  Example {  //  Hold an instance of the class      Private  Static   $ Instance  ;  //  A private constructor; prevents direct creation of Object      Private   Function  _ Construct (){  Echo 'I am constructed' ;}  //  The Singleton Method      Public   Static   Function Singleton (){  If (! Isset (SELF :: $ Instance  )){  $ C = _ Class __  ; Self :: $ Instance = New   $ C  ;}  Return SELF :: $ Instance ;}  //  Example Method      Public   Function  Bark (){  Echo 'Woof! ' ;}  //  Prevent users to clone the instance      Public   Function  _ Clone (){  Trigger_error ('Clone is not allowed .',E_user_error  );}} ?>

Usage:

 
   php  ///   This wocould fail because the constructor is private   $ test  =  New   example;  ///   This will always retrieve a singl E instance of the class   $ test  = example:  Singleton ();   $ test ->  bark ();   //   This will issue an e_user_error.   $ test_clone  =  clone  ( $ test  ); ?> 

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.