您的位置:首页 > 编程语言 > PHP开发

php 工厂模式

2016-06-12 16:07 260 查看
<body>
<?php

//设计模式:工厂模式
/*
class YunSuan
{
public $a;
public $b;

function Jia()
{
return ($this->a+$this->b);
}
function Jian()
{
return ($this->a-$this->b);
}
function Cheng()
{
return ($this->a*$this->b);
}
function Chu()
{
return ($this->a/$this->b);
}
function Yu()
{
return ($this->a%$this->b);
}
}

$y = new YunSuan();
$y->a = 10;
$y->b = 5;

echo $y->Jia();*/

//造父类,用子类继承
class YunSuan
{
public $a;
public $b;

function YunSuan()
{
}
}

//加法的子类
class Jia extends YunSuan
{
function YunSuan()
{
return ($this->a+$this->b);
}
}

//减法的子类
class Jian extends YunSuan
{
function YunSuan()
{
return ($this->a-$this->b);
}
}

$y = new Jian();

$y->a = 10;
$y->b = 5;

//echo $y->YunSuan();

//再优化,工厂类

class GongChang
{

static function DuiXiang($f)
{
switch($f)
{
case "+":
return new Jia();
break;
case "-":
return new Jian();
break;
case "*":
return new Cheng();
break;
}

}
}

$r = GongChang::DuiXiang("-");
$r->a=10;
$r->b = 5;
echo $r->YunSuan();

/*

class Suan
{
public $total;

function Jia($a)
{
$this->total = $this->total+$a;
return $this->total;
}
function Jian($a)
{
$this->total = $this->total-$a;
}
}*/

?>
</body>
</html>


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: