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
    浅复制时,变量的资源号不变。 深复制时,是把成员从新创建的。

  • 相关阅读:
    解决servlet在web.xml中的路径跳转问题
    浅谈上市公司期权
    spring 与mybatis 整合总结
    学习ssm心得
    django中ORM的事务操作
    Celery快速入门
    vagrant 使用指南
    数据库之mysql
    python之pip
    linux基础
  • 原文地址:https://www.cnblogs.com/ghjbk/p/6670238.html
Copyright © 2011-2022 走看看