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

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

PHP中文网
PHP中文网Original
2016-05-26 08:19:031218Durchsuche

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

                   

                   

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn