欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

PHP设计模式之中介者模式

程序员文章站 2022-06-01 13:22:45
...
中介者: 中介者设计莫用于开发一个对象,这个对象能够在类似对象相互之间不直接交互的情况下传送或调节对这些对象的集合的修改
处理具有类似属性并且属性需要保持同步的非耦合对象时,最佳的做法是使用基于中介者设计模式的对象。
  1. /**
  2. * 测试用例描述:示例代码不仅允许乐队进入和管理他们的音乐合集,而且还允许乐队更新他们的配置文件,修改乐队相关信息以及更新其CD信息
  3. *        现在,艺术家可上传MP3集合并从Web站点撤下CD。 因此, Web站点需要保持相对应的CD和MP3彼此同步。
  4. */
  5. //CD类
  6. class CD {
  7. public $band = '';
  8. public $title = '';
  9. protected $_mediator;
  10. public function __construct(MusicContainerMediator $mediator = NULL) {
  11. $this->_mediator = $mediator;
  12. }
  13. public function save() {
  14. //具体实现待定
  15. var_dump($this);
  16. }
  17. public function changeBandName($bandname) {
  18. if ( ! is_null($this->_mediator)) {
  19. $this->_mediator->change($this, array("band" => $bandname));
  20. }
  21. $this->band = $bandname;
  22. $this->save();
  23. }
  24. }
  25. //MP3Archive类
  26. class MP3Archive {
  27. protected $_mediator;
  28. public function __construct(MusicContainerMediator $mediator = NULL) {
  29. $this->_mediator = $mediator;
  30. }
  31. public function save() {
  32. //具体实现待定
  33. var_dump($this);
  34. }
  35. public function changeBandName($bandname) {
  36. if ( ! is_null($this->_mediator)) {
  37. $this->_mediator->change($this, array("band" => $bandname));
  38. }
  39. $this->band = $bandname;
  40. $this->save();
  41. }
  42. }
  43. //中介者类
  44. class MusicContainerMediator {
  45. protected $_containers = array();
  46. public function __construct() {
  47. $this->_containers[] = "CD";
  48. $this->_containers[] = "MP3Archive";
  49. }
  50. public function change($originalObject, $newValue) {
  51. $title = $originalObject->title;
  52. $band = $originalObject->band;
  53. foreach ($this->_containers as $container) {
  54. if ( ! ($originalObject instanceof $container)) {
  55. $object = new $container;
  56. $object->title = $title;
  57. $object->band = $band;
  58. foreach ($newValue as $key => $val) {
  59. $object->$key = $val;
  60. }
  61. $object->save();
  62. }
  63. }
  64. }
  65. }
  66. //测试实例
  67. $titleFromDB = "Waste of a Rib";
  68. $bandFromDB = "Never Again";
  69. $mediator = new MusicContainerMediator();
  70. $cd = new CD($mediator);
  71. $cd->title = $titleFromDB;
  72. $cd->band = $bandFromDB;
  73. $cd->changeBandName("Maybe Once More");
  74. ?>

数据库脚本请参照:http://www.cxybl.com/html/wlbc/Php/2011_1126_9458.html