php工厂模式例子,php设计模式之工厂模式的实例代码

/**

*php设计模式 工厂模式

*site http://www.jquerycn.cn

*/

class FruitFactory {

private $history, $class, $constructor_args;

/**

* Create a factory of given class. Accepts extra arguments to be passed to

* class constructor.

*/

function __construct( $class ) {

var_dump($args = func_get_args());

$this->class = $class;//类名

$this->constructor_args = array_slice( $args, 1 );//参数

}

function __call( $method, $args ) {

$this->history[] = array(

'action' => 'call',

'method' => $method,

'args'    => $args

);

var_dump($this->history);

}

function __set( $property, $value ) {

$this->history[] = array(

'action' => 'set',

'property' => $property,

'value' => $value

);

var_dump($this->history);

}

/**

* Creates an instance and performs all operations that were done on this MagicFactory

*/

function instance() {

# use Reflection to create a new instance, using the $args

$reflection_object = new ReflectionClass( $this->class );

$object = $reflection_object->newInstanceArgs( $this->constructor_args );

foreach( $this->history as $item ) {

if( $item['action'] == 'call' ) {

//运行实例的方法

call_user_func_array( array( $object, $item['method'] ), $item['args'] );

}//属性赋值

if( $item['action'] == 'set' ) {

$object->{$item['property']} = $item['value'];

}

}

# Done

return $object;

}

}

class Fruit {

private $name, $color;

public $price;

function __construct( $name, $color ) {

$this->name = $name;

$this->color = $color;

}

function setName( $name ) {

$this->name = $name;

}

function introduce() {

print "Hello, this is an {$this->name} {$this->color}, its price is {$this->price} RMB.";

}

}

# Setup a factory

$fruit_factory = new FruitFactory('Fruit', 'Apple', 'Gonn');

$fruit_factory->setName('Apple');

$fruit_factory->price = 2;

# Get an instance

$apple = $fruit_factory->instance();

$apple->introduce();

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值