欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

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

程序员文章站 2022-03-30 13:25:33
...

1. [PHP]代码

<?php
// factory pattern

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

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

				case 'square':
					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('circle', 10);
echo $shape->getArea();
echo "\n";

$shape = Shape::getShape('square', 2);
echo $shape->getArea();
echo "\n";
相关标签: php