Home  >  Article  >  Backend Development  >  Study notes on three commonly used design patterns in PHP

Study notes on three commonly used design patterns in PHP

WBOY
WBOYOriginal
2016-07-25 09:05:46805browse
  1. class SingetonBasic {

  2. private static $instance;

  3. // other vars..

  4. private function __construct() {

  5. // do construct..
  6. }

  7. private function __clone() {}

  8. public static function getInstance() {

  9. if (!(self::$instance instanceof self)) {
  10. self::$instance = new self();
  11. }
  12. return self::$instance;
  13. }

  14. // other functions..

  15. }

  16. $a = SingetonBasic::getInstance();

  17. $b = SingetonBasic::getInstance();
  18. var_dump($a === $b);< ;/p>
Copy code

2. Factory mode The factory pattern allows you to create a class specifically designed to implement and return instances of other classes based on input parameters or application configuration. Example of factory pattern:

  1. class FactoryBasic {
  2. public static function create($config) {

  3. }

  4. }

Copy code

For example, here is a factory that describes shape objects. It hopes to create different shapes based on the number of parameters passed in.

  1. // Define the public functions of the shape: get the perimeter and area.

  2. interface IShape {
  3. function getCircum();
  4. function getArea();
  5. }

  6. // Define the rectangle class

  7. class Rectangle implements IShape {
  8. private $width, $height;
  9. public function __construct($width, $height) {

  10. $this->width = $width;
  11. $this->height = $height;
  12. }

  13. < p>public function getCircum() {
  14. return 2 * ($this->width + $this->height);
  15. }

  16. public function getArea() {

  17. return $this ->width * $this->height;
  18. }
  19. }

  20. // Define circle class

  21. class Circle implements IShape {
  22. private $radii;

  23. < p>public function __construct($radii) {
  24. $this->radii = $radii;
  25. }

  26. public function getCircum() {

  27. return 2 * M_PI * $this-> radii;
  28. }

  29. public function getArea() {

  30. return M_PI * pow($this->radii, 2);
  31. }
  32. }

  33. //Create different shapes based on the number of parameters passed in.

  34. class FactoryShape {
  35. public static function create() {
  36. switch (func_num_args()) {
  37. case 1:
  38. return new Circle(func_get_arg(0));
  39. break;
  40. case 2:
  41. return new Rectangle(func_get_arg(0) ), func_get_arg(1));
  42. break;

  43. }

  44. }
  45. }

  46. // Rectangular object

  47. $c = FactoryShape::create(4 , 2);
  48. var_dump($c->getArea());
  49. // Circle object
  50. $o = FactoryShape::create(2);
  51. var_dump($o->getArea());
Copy code

Using the factory pattern makes it easier to call methods, because it only has one class and one method. If the factory pattern is not used, you have to decide which class and which method should be called when calling; using the factory pattern also makes it easier to call methods in the future. It is easier for the application to make changes. For example, to add support for a shape, you only need to modify the create() method in the factory class. Instead of using the factory pattern, you need to modify the code block that calls the shape.

3. Observer mode The Observer pattern gives you another way to avoid tight coupling between components. The pattern is very simple: an object makes itself observable by adding a method that allows another object, the observer, to register itself. When an observable object changes, it sends messages to registered observers. These observers use this information to perform operations independent of the observable object. The result is that objects can talk to each other without having to understand why.

A simple example: when a listener is listening to a radio station (i.e. the radio station joins a new listener), it will send out a prompt message, which can be observed by the log observer who sent the message.

  1. // Observer interface
  2. interface IObserver {
  3. function onListen($sender, $args);
  4. function getName();
  5. }

  6. // Observable interface

  7. interface IObservable {
  8. function addObserver($observer);
  9. function removeObserver($observer_name);
  10. }

  11. // Observer class

  12. abstract class Observer implements IObserver {
  13. protected $name;

  14. public function getName() {

  15. return $this->name;
  16. }
  17. }

  18. // Observable class

  19. class Observable implements IObservable {
  20. protected $observers = array();

  21. public function addObserver($observer) {

  22. if (!($observer instanceof IObserver)) {
  23. return;
  24. }
  25. $this->observers[] = $observer;
  26. }

  27. public function removeObserver($observer_name) {

  28. foreach ($this->observers as $index = > $observer) {
  29. if ($observer->getName() === $observer_name) {
  30. array_splice($this->observers, $index, 1);
  31. return;
  32. }
  33. }
  34. }
  35. }

  36. // Simulate a class that can be observed: RadioStation

  37. class RadioStation extends Observable {

  38. public function addListener($listener) {

  39. foreach ($ this->observers as $observer) {
  40. $observer->onListen($this, $listener);
  41. }
  42. }
  43. }

  44. // Simulate an observer class

  45. class RadioStationLogger extends Observer {
  46. protected $name = 'logger';

  47. public function onListen($sender, $args) {

  48. echo $args, ' join the radiostation.
    ';
  49. }
  50. }

  51. // Simulate another observer class

  52. class OtherObserver extends Observer {
  53. protected $name = 'other';
  54. public function onListen($sender, $args) {
  55. echo 'other observer..
    ';
  56. }
  57. }

  58. $rs = new RadioStation();

  59. // Inject observers

  60. $rs->addObserver(new RadioStationLogger());
  61. $rs->addObserver(new OtherObserver());

  62. // Remove observers

  63. $rs ->removeObserver('other');

  64. // You can see the observed information

  65. $rs->addListener('cctv');
  66. ?>
Copy code


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