Common php design modes: Factory mode and Singleton mode

Source: Internet
Author: User
Common php design modes: Factory mode and Singleton mode

  1. /**
  2. Example of Factory mode
  3. @ Link http://bbs.it-home.org
  4. */
  5. Abstract class Operation {
  6. Abstract public function getValue ($ num1, $ num2 );
  7. Public function getAttr (){
  8. Return 1;
  9. }
  10. }
  11. Class Add extends Operation {
  12. Public function getValue ($ num1, $ num2 ){
  13. Return $ num1 + $ num2;
  14. }
  15. }
  16. Class Sub extends Operation {
  17. Public function getValue ($ num1, $ num2 ){
  18. Return $ num1-$ num2;
  19. }
  20. }
  21. Class Factory {
  22. Public static function CreateObj ($ operation ){
  23. Switch ($ operation ){
  24. Case '+': return new Add ();
  25. Case '-': return new Sub ();
  26. }
  27. }
  28. }
  29. $ Op = Factory: CreateObj ('-');
  30. Echo $ Op-> getValue (3, 6 );
  31. ?>

In actual development, it is generally used as a database selection class.

Let's look at the Singleton mode of php design mode: Singleton is unique. Simply put, an object is only responsible for a specific task. for example, there is only one phone book in the post office, which can be viewed by people who need it, there is no need for the staff to take out one copy when they want to check it.

  1. Class Mysql {
  2. Public static $ conn;
  3. Public static function getInstance (){
  4. If (! Self: $ conn ){
  5. New self ();
  6. Return self: $ conn;
  7. } Else {
  8. Return self: $ conn;
  9. }
  10. }
  11. Private function _ construct (){
  12. Self: $ conn = "mysql_connect:"; // mysql_connect ('','','')
  13. }
  14. Public function _ clone ()
  15. {
  16. Trigger_error ("Only one connection ");
  17. }
  18. }
  19. Echo Mysql: getInstance ();
  20. Echo Mysql: getInstance ();
  21. ?>

Note: The Singleton mode is generally used as a database connection class and often used together with the factory mode. The Singleton mode can be called based on parameters to improve resource usage efficiency.

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.