zoukankan      html  css  js  c++  java
  • 原型模式

    这种模式主要是复制对象。有点类似单例。但又不相同。 代码如下

    [PHP] 纯文本查看 复制代码
    01
    02
    03
    04
    05
    06
    07
    08
    09
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    <?php
    /**
     * 原型接口
     */
    interface IPrototype
    {
        public function copy($type);
    }
    /**
     * 原型类
     */
    class Prototype implements IPrototype
    {
        public $name;//测试用的
        public function __construct($name)
        {
            $this->name = $name;
        }
        public function copy($type = 1)//复制本身
        {
            return $type == 1 ? $this->copy1() : $this->copy2();
        }
        private function copy1()//浅复制
        {
            return clone $this;
        }
        private function copy2()//深度复制
        {
            return unserialize(serialize($this));
        }
    }
    class Test//测试的一个类。注意看打印的类的 id
    {
        public $test1 = 'test1';
    }
    $prototype1 = new Prototype(new Test());
    var_dump($prototype1); //$prototype1 资源号是1  Test是2
    echo '<hr>';
    $prototype2 = $prototype1->copy(1);//浅复制
    var_dump($prototype2);//$prototype2 资源号是3  Test仍然是2
    echo '<hr>';
    $prototype3 = $prototype1->copy(0);//深复制
    var_dump($prototype3);//$prototype3 资源号是4  test是5
     
     
    ?>


    结果如下

    object(Prototype)#1 (1) { ["name"]=> object(Test)#2 (1) { ["test1"]=> string(5) "test1" } }
    object(Prototype)#3 (1) { ["name"]=> object(Test)#2 (1) { ["test1"]=> string(5) "test1" } }
    object(Prototype)#4 (1) { ["name"]=> object(Test)#5 (1) { ["test1"]=> string(5) "test1" } }

    注意结果中的资源号   分别是
    #1 #2   
    #3 #2
    #4 #5
    浅复制时,变量的资源号不变。 深复制时,是把成员从新创建的。

  • 相关阅读:
    第二次作业——评分!
    第一次点评!
    神经网络测试:利用分块patch输入的弊端
    利用分块进行网络输入测试
    python 用filter求解素数
    英语语法
    git clone 下载出现Time out
    路由转发
    获取用户密码
    后门维持
  • 原文地址:https://www.cnblogs.com/ghjbk/p/6670238.html
Copyright © 2011-2022 走看看