ホームページ  >  記事  >  php教程  >  简单的一个php工厂模式代码

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

PHP中文网
PHP中文网オリジナル
2016-05-26 08:19:031218ブラウズ

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

                   

                   

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。