php 设计模式之 单例模式
程序员文章站
2023-12-24 14:39:33
小船类boat.php复制代码 代码如下:
小船类boat.php
<?php
class boat {
private static $instance=null;
private $skipper;
private $personnum=0;
private $passengers=array();
private function __construct() {
}
public static function getinstance(){
if (self::$instance==null){
self::$instance=new boat();
}
return self::$instance;
}
/**
* 设置船长
*
* @param unknown_type $name
*/
public function setskipper($name){
$this->skipper=$name;
}
/**
* 装人
*
* @param unknown_type $person
*/
public function load($person){
if (!emptyempty($person) and $this->personnum<=5){
array_push($this->passengers,$person);
$this->personnum=$this->personnum+1;
}
if ($this->personnum>5) {
echo 'this boat only load 5 person!';
}
}
/**
* 船上装了什么人
*
* @return unknown
*/
public function whoinboat(){
return $this->passengers;
}
}
?>
现在看看怎么样上客
<?php
include 'boat.php';
echo "从前有一条河,河里只有一条船,<br>";
$boat1=boat::getinstance();//因为只有一条船,所以只有一个实例
echo "现在张三要到河东去,";
$boat1->load('张三');
echo "<br>现在船上坐着:<br>";
foreach ($boat1->whoinboat() as $who){
echo $who.'<br>';
}
echo "<br>现在李四也要过河东去<br>";
$boat1->load('李四');
echo "现在船上坐着:<br>";
foreach ($boat1->whoinboat() as $who){
echo $who.'、';
}
echo "<br><br>王五以为这条河有另一条船,<br>";
$boat2=boat::getinstance();
echo "他现在上船<br>";
$boat2->load('王五');
echo "现在船上坐着:<br>";
foreach ($boat1->whoinboat() as $who){
echo $who.'、';
}
?>
复制代码 代码如下:
<?php
class boat {
private static $instance=null;
private $skipper;
private $personnum=0;
private $passengers=array();
private function __construct() {
}
public static function getinstance(){
if (self::$instance==null){
self::$instance=new boat();
}
return self::$instance;
}
/**
* 设置船长
*
* @param unknown_type $name
*/
public function setskipper($name){
$this->skipper=$name;
}
/**
* 装人
*
* @param unknown_type $person
*/
public function load($person){
if (!emptyempty($person) and $this->personnum<=5){
array_push($this->passengers,$person);
$this->personnum=$this->personnum+1;
}
if ($this->personnum>5) {
echo 'this boat only load 5 person!';
}
}
/**
* 船上装了什么人
*
* @return unknown
*/
public function whoinboat(){
return $this->passengers;
}
}
?>
现在看看怎么样上客
复制代码 代码如下:
<?php
include 'boat.php';
echo "从前有一条河,河里只有一条船,<br>";
$boat1=boat::getinstance();//因为只有一条船,所以只有一个实例
echo "现在张三要到河东去,";
$boat1->load('张三');
echo "<br>现在船上坐着:<br>";
foreach ($boat1->whoinboat() as $who){
echo $who.'<br>';
}
echo "<br>现在李四也要过河东去<br>";
$boat1->load('李四');
echo "现在船上坐着:<br>";
foreach ($boat1->whoinboat() as $who){
echo $who.'、';
}
echo "<br><br>王五以为这条河有另一条船,<br>";
$boat2=boat::getinstance();
echo "他现在上船<br>";
$boat2->load('王五');
echo "现在船上坐着:<br>";
foreach ($boat1->whoinboat() as $who){
echo $who.'、';
}
?>