工厂模式(factory pattern) 2015-09-27 | 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586interface Shape{ public function getCircum(); public function getArea();}//矩形class Rectangle implements Shape{ private $width, $height; public function __construct($width, $height) { $this->width = $width; $this->height = $height; } public function getCircum() { return ($this->width + $this->height) * 2; } public function getArea() { return $this->width * $this->height; }}class Circle implements Shape{ private $radii; public function __construct($radii) { $this->radii = $radii; } public function getCircum() { // TODO: Implement getCircum() method. return 2 * M_PI * $this->radii; } public function getArea() { // TODO: Implement getArea() method. return M_PI * pow($this->radii, 2); }}// 创建工厂class Factory{ public static function create() { //判断穿过来的参数个数 switch (func_num_args()) { case 1: return new Circle(func_get_arg(0)); break; case 2: return new Rectangle(func_get_arg(0), func_get_arg(1)); break; } }}$rectangle = Factory::create(4,2);echo $rectangle->getCircum()." ";echo $rectangle->getArea()." ";$circle = Factory::create(3);echo $circle->getCircum()." ";echo $circle->getArea(); 分享即是成长 打赏 微信支付 本文作者: changyuan 本文链接: http://changyuan.github.io/2015/09/27/factory-pattern/ 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!