note 86119 deleted from language.oop5.patterns by danbrown
| From: | danbrown@php.net | Date: | Sun, 23 Jan 2011 16:36:24 +0000 |
| Subject: | note 86119 deleted from language.oop5.patterns by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176095@lists.php.net to get a copy of this message | ||
Note Submitter: wbcarts at juno dot com
----
"Red-Necked" SINGLETON STYLE
I'm not sure if this is a so-called "pattern" because I'm only using plain
ol' static data - nuttin fancier than that. It seems to fit the singleton pattern you guys have
been describing, but without private constructors, or references to itself. Here's my singleton
class... after it's been country-fried!
<?php
class MutableSingletonModel {
public static $data1 = 1;
public static $data2 = 1;
public static function getInstance() {
return new MutableSingletonModel();
}
public function getData1() {
return self::$data1;
}
public function getData2() {
return self::$data2;
}
public function setData1($value) {
if($value > 0 && $value < 100) self::$data1 = $value;
}
public function setData2($value) {
if($value > 0 && $value < 100) self::$data2 = $value;
}
public function __toString() {
return 'MutableSingletonModel[data1=' . self::$data1 . ', data2=' .
self::$data2 . ']';
}
}
// try to set data before any objects is created
MutableSingletonModel::$data1 = 55;
$msm1 = MutableSingletonModel::getInstance(); // use the getInstance() method
$msm2 = new MutableSingletonModel(); // use the default constructor
$msm2->setData2(78); // set data with an instantiated object
echo $msm1 . '<br>';
echo $msm2 . '<br>';
echo MutableSingletonModel::getInstance() . '<br>';
echo (new MutableSingletonModel());
?>
Each echo above writes: MutableSingletonModel[data1=55, data2=78]
... Now, I had a really hard time to crack the mystery of the private constructor. To me, any
"data", "object", or "thing", of which there is only one, doesn't
require "no way to construct it". Furthermore, how can an object (of which there is only
one), contain another object of itself inside? Next time I buy a new Cadillac, I'm definitely
gonna check the trunk for another!