Rumah  >  Artikel  >  php教程  >  简单的一个php工厂模式代码

简单的一个php工厂模式代码

PHP中文网
PHP中文网asal
2016-05-26 08:19:031218semak imbas

1. [PHP]代码   

<?php
// factory pattern

class Shape {
	static public function getShape($type, $dimension) {

		if ($type && $dimension) 
		{
			switch($type)
			{
				case &#39;circle&#39;:
					return new Circle($dimension);
				break;

				case &#39;square&#39;:
					return new Square($dimension);
				break;

				default:
					throw new Exception("Unrecognized shape");					
				break;
			}			
		}
	}
}

class Circle {
	private $radius = 0;
	public function __construct($radius) {
		$this->radius = $radius;
	}
	public function getArea() {
		return $this->radius * $this->radius * pi();
	}
}

class Square {
	private $side = 0;
	public function __construct($side) {
		$this->side = $side;
	}
	public function getArea() {
		return $this->side * $this->side;
	}
}

$shape = Shape::getShape(&#39;circle&#39;, 10);
echo $shape->getArea();
echo "\n";

$shape = Shape::getShape(&#39;square&#39;, 2);
echo $shape->getArea();
echo "\n";

                   

                   

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn