Home  >  Article  >  php教程  >  简单的一个php工厂模式代码

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

PHP中文网
PHP中文网Original
2016-05-26 08:19:031217browse

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";

                   

                   

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn