Home > php教程 > PHP源码 > body text

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

PHP中文网
Release: 2016-05-26 08:19:03
Original
1246 people have browsed it

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";
Copy after login

                   

                   

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template