设计模式 -原型模式(三)

一、什么是原型模式

原型模式简单理解:先创建好一个原型对象,然后通过clone原型对象,来创建新的对象。

二、使用原型模式的好处

原型模式适用于大对象的创建,比如一个对象创建的时候需要初始化很多东西,产生大的开销,这时候用原型模式,就可以避免类创建时重复初始化的开销。

三、具体实现

1、比如有以下A对象:

class A
{
	public $color;
	
	public $height;
	
	public $width;
	
	// 开销比较大的初始化
	public function init(string $color = 'green', int $height = 100, int $width = 100)
	{
		$this->color  = $color;
		$this->height = $height;
		$this->width  = $width;
		// long long code ...
	}
	public function height()
	{
		return $this->height;
	}
}

2、未使用原型模式调用

$test1 = new A();
$test1->init();
$height1 = $test1->height();

$test2 = new A();
$test2->init();
$height2 = $test2->height();

3、使用原型对象模式调用

$prototype = new A();	// 创建原型对象
$prototype->init();

$test1 = clone $prototype; // 克隆原型对象
$height1 = $test1->height();

$test2 = clone $prototype;
$height2 = $test2->height();

有什么不懂的评论见哈,看懂的帮忙点个赞!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值