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
本文原创发布php中文网,转载请注明出处,感谢您的尊重!