Home > Backend Development > PHP Tutorial > Introduction to Factory Pattern and Singleton Pattern of PHP Common Design Patterns

Introduction to Factory Pattern and Singleton Pattern of PHP Common Design Patterns

WBOY
Release: 2016-07-25 09:05:19
Original
806 people have browsed it
  1. /**
  2. Example of factory pattern
  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. ?>
Copy code

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

Let’s look at the singleton mode of PHP design pattern: a singleton is the only one that exists. Simply put, an object is only responsible for a specific task; For example, there is only one phone book in the post office. People who need it can read it. There is no need for the staff to take out one copy when everyone wants to check it, and then recycle it after reading.

  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. ?>
Copy code

Instructions: The singleton mode is mostly used as a database connection class and is often used together with the factory mode. Calling the singleton mode according to parameters can improve resource usage efficiency.



source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template