• 第九章 简历复印 --- 原型模式

    第九章 简历复印 --- 原型模式

    1. <?php
    2. class Company
    3. {
    4. private $company;
    5. public function setName($name)
    6. {
    7. $this->company = $name;
    8. }
    9. public function getName()
    10. {
    11. return $this->company;
    12. }
    13. }
    14. class Resume
    15. {
    16. private $name;
    17. private $sex;
    18. private $age;
    19. private $timeArea;
    20. private $company;
    21. function __construct($name)
    22. {
    23. $this->name = $name;
    24. $this->company = new Company();
    25. }
    26. public function setPersonalInfo($sex, $age)
    27. {
    28. $this->sex = $sex;
    29. $this->age = $age;
    30. }
    31. public function setWorkExperience($timeArea, $company)
    32. {
    33. $this->timeArea = $timeArea;
    34. $this->company->setName($company);
    35. }
    36. public function display()
    37. {
    38. echo $this->name." ".$this->sex." ".$this->age."\n";
    39. echo $this->timeArea." ".$this->company->getName()."\n";
    40. }
    41. // 对引用执行深复制
    42. function __clone()
    43. {
    44. $this->company = clone $this->company;
    45. }
    46. }
    47. // 客户端代码
    48. $resume = new Resume("大鸟");
    49. $resume->setPersonalInfo("男", 29);
    50. $resume->setWorkExperience("1998-2000","xxx 公司");
    51. $resume2 = clone $resume;
    52. $resume2->setPersonalInfo("男", 40);
    53. $resume2->setWorkExperience("1998-2010","xx 公司");
    54. $resume->display();
    55. $resume2->display();

    总结:

    原型模式,用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

    原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需要知道任何创建的细节。

    一般在初始化的信息不发生变化的情况下,克隆是最好的办法。既隐藏了对象创建的细节,又对性能是大大的提高。

    上一章:第八章 雷锋依然在人间 --- 工厂方法模式

    下一章:第十章 考题抄错会做也白搭 --- 模版方法模式