若转载教程,请注明出自SW-X框架官方文档!

    1. ?php
    2. /**
    3. * 设计模式之原型模式
    4. * 小黄牛
    5. */
    6. header("Content-type: text/html; charset=utf-8");
    7. /**
    8. * 抽象 - 原型类
    9. */
    10. abstract class Prototype{
    11. abstract function cloned(); // 克隆方法
    12. }
    13. /**
    14. * 具体化 - 原型类
    15. */
    16. class Plane extends Prototype{
    17. public $color; // 测试的成员属性
    18. public function cloned(){
    19. # clone 关键字,是PHP5才有的,用于克隆一个实例
    20. return clone $this;
    21. }
    22. }
    23. # 测试
    24. $res1 = new Plane();
    25. $res1->color = '蓝色'; // 赋值成员属性
    26. $res2 = $res1->cloned(); // 克隆一个实例
    27. echo "res1的颜色为:{$res1->color}<br/>";
    28. echo "res2的颜色为:{$res2->color}<br/>";

    浏览器输出

    1. res1的颜色为:蓝色
    2. res2的颜色为:蓝色

    原型模式

    1. 1.抽象原型,提供了一个克隆的接口
    2. 2.具体的原型,实现克隆的接口

    这里只是介绍一下原型模式的核心思想,其实在实际开发中直接clone即可。