background image

工厂模式在于可以根据输入参数或者应用程序配置的不同来创建一种专门用来实现化并
返回其它类的实例的类。下面是一个最基本的工厂模式:
代码如下:
 

class

 FactoryBasic {

public

 

static

 

function

 create(

$config

) {

}
}
比如这里是一个描述形状对象的工厂,它希望根据传入的参数个数不同来创建不同的形
状。
代码如下:
 

// 定义形状的公共功能:获取周长和面积。
interface

 IShape {

function

 getCircum();

function

 getArea();

}

// 定义矩形类
class

 Rectangle 

implements

 IShape {

private

 

$width

$height

;

public

 

function

 __construct(

$width

$height

) {

$this

->width = 

$width

;

$this

->height = 

$height

;

}

public

 

function

 getCircum() {

return

 2 * (

$this

->width + 

$this

->height);

}

public

 

function

 getArea() {

return

 

$this

->width * 

$this

->height;

}
}

// 定义圆类
class

 Circle 

implements

 IShape {

private

 

$radii

;

public

 

function

 __construct(

$radii

) {

$this

->radii = 

$radii

;

}

public

 

function

 getCircum() {

return

 2 * M_PI * 

$this

->radii;

}

public

 

function

 getArea() {