php 设计模式之 单例模式

前端之家收集整理的这篇文章主要介绍了php 设计模式之 单例模式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

小船类boat.PHP
<div class="codetitle"><a style="CURSOR: pointer" data="47573" class="copybut" id="copybut47573" onclick="doCopy('code47573')"> 代码如下:

<div class="codebody" id="code47573">
<?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;
}
}
?>

现在看看怎么样上客
<div class="codetitle"><a style="CURSOR: pointer" data="39287" class="copybut" id="copybut39287" onclick="doCopy('code39287')"> 代码如下:
<div class="codebody" id="code39287">
<?PHP
include 'boat.PHP';
echo "从前有一条河,河里只有一条船,
";
$boat1=boat::getInstance();//因为只有一条船,所以只有一个实例
echo "现在张三要到河东去,";
$boat1->load('张三');
echo "
现在船上坐着:
";
foreach ($boat1->whoInboat() as $who){
echo $who.'
';
}
echo "
现在李四也要过河东去
";
$boat1->load('李四');
echo "现在船上坐着:
";
foreach ($boat1->whoInboat() as $who){
echo $who.'、';
}
echo "

王五以为这条河有另一条船,
";
$boat2=boat::getInstance();
echo "他现在上船
";
$boat2->load('王五');
echo "现在船上坐着:
";
foreach ($boat1->whoInboat() as $who){
echo $who.'、';
}
?>

原文链接:https://www.f2er.com/php/29356.html

猜你在找的PHP相关文章