原型模式

前言:

    原型模式:利用clone方法,复制出新的对象

    看到这里,你肯定会有疑问,这不是和工厂模式很类似的吗?也是不停的生产出新的对象.

    那么它究竟和工厂模式有什么具体的区别呢?

    下面就是答案:       

     (转)使用原型模式创建对象比直接new一个对象在性能上要好的多,因为Object类的clone方法是一个本地方法,它直接操作内存中的二进制流,特别是复制大对象时,性能的差别非常明显。


<?php

/**定义一个Prototype原型的接口
 * Interface Prototype
 */
interface Prototype{
    public function copy();
}

/**
 * 子类去继承Prototype原型接口,并且实现copy方法
 * Class Student
 */
class Student implements Prototype{
    public $name;
    public $age;
    public $sex;
    public function __construct($name,$age,$sex){
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    public function getStudentInformation(){
        echo "student name is ".$this->name." student age is".$this->age." student sex is".$this->sex;
    }
    public function copy(){
        return clone $this;
    }
}
$student1=new Student("dennis","26","man");
//$student1->getStudentInformation();

$student2=$student1->copy();
$student2->name = "Jack";
$student2->getStudentInformation();

    

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值