原型模式

原型模式

  • 深复制和浅复制

<?php
/**
 * 原型模式
 */

// 原型接口
InterFace Prototype
{
    public function copy();
}

// 实现类
class People implements Prototype
{
    public $name;
    public $age;
    public function __construct($name, $age)
    {
        $this->name = $name;
        $this->age = $age;
    }
    public function display()
    {
        print_r($this->name . "\n");
        print_r($this->age . "\n");
    }
    public function copy()
    {
        return clone $this;
    }
}

// main
$p1 = new People('张三',23);
$p1->display();

$p2 = $p1->copy();
$p2->name = '李四';
$p2->display();

评论

暂无评论