Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> Rozszerzalny singleton
Orzeszekk
post
Post #1





Grupa: Zarejestrowani
Postów: 260
Pomógł: 14
Dołączył: 8.09.2011

Ostrzeżenie: (0%)
-----


  1. <?php
  2. /**
  3.  * Rozszerzalny singleton.
  4.  *
  5.  * <b>Użycie</b>
  6.  * <ul><li>W każdej klasie pochodnej utwórz protected static $instance</li>
  7.  * <li>Konstruktor kazdej klasy pochodnej musi byc chroniony lub prywatny</li></ul>
  8.  */
  9. class Singleton
  10. {
  11. /** To jest do celow testowych */
  12. protected $nazwa;
  13. protected static $instance;
  14. protected function __construct()
  15. {
  16. }
  17. public static function get()
  18. {
  19. if (!(static::$instance))
  20. {
  21. $className = get_called_class();
  22. $className::$instance = new $className;
  23. }
  24. return static::$instance;
  25. }
  26. public function identify()
  27. {
  28. echo $this->nazwa;
  29. }
  30. }
  31. class Pierwsza extends Singleton
  32. {
  33. public static $instance;
  34. protected function __construct()
  35. {
  36. $this->nazwa = "pierwsza";
  37. }
  38. }
  39. class Druga extends Singleton
  40. {
  41. public static $instance;
  42. protected function __construct()
  43. {
  44. $this->nazwa = "druga";
  45. }
  46. }
  47. class Trzecia extends Druga
  48. {
  49. public static $instance;
  50. protected function __construct()
  51. {
  52. $this->nazwa = "trzecia";
  53. }
  54. }
  55. $pierwsza = Pierwsza::get();
  56. $druga = Druga::get();
  57. $trzecia = Trzecia::get();
  58. $trzecia->identify();
  59. $pierwsza->identify();
  60. $druga->identify();
  61. ?>


Jak go ulepszyc bym nie musial deklarowac w kazdej klasie public static $instance?

jesli usune deklaracje tych zmiennych statycznych z klas to wtedy tworzy mi singleton zamiast klasy tej co trzeba (IMG:style_emoticons/default/biggrin.gif) (ew w przypadku klasy trzecia utworzy mi klase druga).

Ten post edytował Orzeszekk 7.11.2011, 11:46:45
Go to the top of the page
+Quote Post

Posty w temacie


Reply to this topicStart new topic
2 Użytkowników czyta ten temat (2 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 26.09.2025 - 13:50