php设计模式遵循的原则

php设计模式遵循的原则

在讨论面向对象编程和模式(具体一点来说,设计模式)的时候,我们需要一些标准来对设计的好还进行判断,或者说应该遵循怎样的原则和指导方针。

现在,我们就来了解下这些原则:

  • 单一职责原则(S)
  • 开闭原则(O)
  • 里氏替换原则(L)
  • 接口隔离原则(I)
  • 依赖倒置原则(D)
  • 合成复用原则
  • 及迪米特法则(最少知道原则)

本文将涵盖 SOLID + 合成复用原则的讲解及示例,迪米特法则以扩展阅读形式给出。

单一职责原则(Single Responsibility Principle[SRP]) ★★★★

一个类只负责一个功能领域中的相应职责(只做一类事情)。或者说一个类仅能有一个引起它变化的原因。

来看看一个功能过重的类示例:

 
  1. /**

  2. * CustomerDataChart 客户图片处理

  3. */

  4. class CustomerDataChart

  5. {

  6. /**

  7. * 获取数据库连接

  8. */

  9. public function getConnection()

  10. {

  11. }

  12.  
  13. /**

  14. * 查找所有客户信息

  15. */

  16. public function findCustomers()

  17. {

  18. }

  19.  
  20. /**

  21. * 创建图表

  22. */

  23. public function createChart()

  24. {

  25. }

  26.  
  27. /**

  28. * 显示图表

  29. */

  30. public function displayChart()

  31. {

  32. }

  33. }

我们发现 CustomerDataChart 类完成多个职能:

  • 建立数据库连接
  • 查找客户
  • 创建和显示图表

此时,其它类若需要使用数据库连接,无法复用 CustomerDataChart;或者想要查找客户也无法实现复用。另外,修改数据库连接或修改图表显示方式都需要修改 CustomerDataChart 类。这个问题挺严重的,无论修改什么功能都需要多这个类进行编码。

所以,我们采用 单一职责原则 对类进行重构,如下:

 
  1. /**

  2. * DB 类负责完成数据库连接操作

  3. */

  4. class DB

  5. {

  6. public function getConnection()

  7. {

  8. }

  9. }

  10.  
  11. /**

  12. * Customer 类用于从数据库中查找客户记录

  13. */

  14. class Customer

  15. {

  16. private $db;

  17.  
  18. public function __construct(DB $db)

  19. {

  20. $this->db = $db;

  21. }

  22.  
  23. public function findCustomers()

  24. {

  25. }

  26. }

  27.  
  28. class CustomerDataChart

  29. {

  30. private $customer;

  31.  
  32. public function __construct(Customer $customer)

  33. {

  34. $this->customer = $customer;

  35. }

  36.  
  37. /**

  38. * 创建图表

  39. */

  40. public function createChart()

  41. {

  42. }

  43.  
  44. /**

  45. * 显示图表

  46. */

  47. public function displayChart()

  48. {

  49. }

  50. }

重构完成后:

  • DB 类仅处理数据库连接的问题,挺提供 getConnection() 方法获取数据库连接;
  • Customer 类完成操作 Customers 数据表的任务,这其中包括 CRUD 的方法;
  • CustomerDataChart 实现创建和显示图表。

各司其职,配合默契,完美!

开闭原则(Open-Closed Principle[OCP]) ★★★★★

开闭原则 是 最重要 的面向对象设计原则,是可复用设计的基石。

「开闭原则」:对扩展开放、对修改关闭,即尽量在不修改原有代码的基础上进行扩展。要想系统满足「开闭原则」,需要对系统进行 抽象

通过 接口 或 抽象类 将系统进行抽象化设计,然后通过实现类对系统进行扩展。当有新需求需要修改系统行为,简单的通过增加新的实现类,就能实现扩展业务,达到在不修改已有代码的基础上扩展系统功能这一目标。

示例,系统提供多种图表展现形式,如柱状图、饼状图,下面是不符合开闭原则的实现:

 
  1. <?php

  2.  
  3. /**

  4. * 显示图表

  5. */

  6. class ChartDisplay

  7. {

  8. private $chart;

  9.  
  10. /**

  11. * @param string $type 图标实现类型

  12. */

  13. public function __construct(string $type)

  14. {

  15. switch ($type) {

  16. case 'pie':

  17. $this->chart = new PieChart();

  18. break;

  19.  
  20. case 'bar':

  21. $this->chart = new BarChart();

  22. break;

  23.  
  24. default:

  25. $this->chart = new BarChart();

  26. }

  27.  
  28. return $this;

  29. }

  30.  
  31. /**

  32. * 显示图标

  33. */

  34. public function display()

  35. {

  36. $this->chart->render();

  37. }

  38. }

  39.  
  40. /**

  41. * 饼图

  42. */

  43. class PieChart

  44. {

  45. public function render()

  46. {

  47. echo 'Pie chart.';

  48. }

  49. }

  50.  
  51. /**

  52. * 柱状图

  53. */

  54. class BarChart

  55. {

  56. public function render()

  57. {

  58. echo 'Bar chart.';

  59. }

  60. }

  61.  
  62. $pie = new ChartDisplay('pie');

  63. $pie->display(); //Pie chart.

  64.  
  65. $bar = new ChartDisplay('bar');

  66. $bar->display(); //Bar chart.

在这里我们的 ChartDisplay 每增加一种图表显示,都需要在构造函数中对代码进行修改。所以,违反了 开闭原则。我们可以通过声明一个 Chart 抽象类(或接口),再将接口传入 ChartDisplay 构造函数,实现面向接口编程。

 
  1.  
  2. /**

  3. * 图表接口

  4. */

  5. interface ChartInterface

  6. {

  7. /**

  8. * 绘制图表

  9. */

  10. public function render();

  11. }

  12.  
  13. class PieChart implements ChartInterface

  14. {

  15. public function render()

  16. {

  17. echo 'Pie chart.';

  18. }

  19. }

  20.  
  21. class BarChart implements ChartInterface

  22. {

  23. public function render()

  24. {

  25. echo 'Bar chart.';

  26. }

  27. }

  28.  
  29. /**

  30. * 显示图表

  31. */

  32. class ChartDisplay

  33. {

  34. private $chart;

  35.  
  36. /**

  37. * @param ChartInterface $chart

  38. */

  39. public function __construct(ChartInterface $chart)

  40. {

  41. $this->chart = $chart;

  42. }

  43.  
  44. /**

  45. * 显示图标

  46. */

  47. public function display()

  48. {

  49. $this->chart->render();

  50. }

  51. }

  52.  
  53. $config = ['PieChart', 'BarChart'];

  54.  
  55. foreach ($config as $key => $chart) {

  56. $display = new ChartDisplay(new $chart());

  57. $display->display();

  58. }

修改后的 ChartDisplay 通过接收 ChartInterface 接口作为构造函数参数,实现了图表显示不依赖于具体的实现类即 面向接口编程。在不修改源码的情况下,随时增加一个 LineChart 线状图表显示。具体图表实现可以从配置文件中读取。

里氏替换原则(Liskov Substitution Principle[LSP]) ★★★★★

里氏代换原则:在软件中将一个基类对象替换成它的子类对象,程序将不会产生任何错误和异常,反过来则不成立。如果一个软件实体使用的是一个子类对象的话,那么它不一定能够使用基类对象。

示例,我们的系统用户类型分为:普通用户(CommonCustomer)和 VIP 用户(VipCustomer),当用户收到留言时需要给用户发送邮件通知。原系统设计如下:

 
  1. <?php

  2.  
  3. /**

  4. * 发送邮件

  5. */

  6. class EmailSender

  7. {

  8. /**

  9. * 发送邮件给普通用户

  10. *

  11. * @param CommonCustomer $customer

  12. * @return void

  13. */

  14. public function sendToCommonCustomer(CommonCustomer $customer)

  15. {

  16. printf("Send email to %s[%s]", $customer->getName(), $customer->getEmail());

  17. }

  18.  
  19. /**

  20. * 发送邮件给 VIP 用户

  21. *

  22. * @param VipCustomer $vip

  23. * @return void

  24. */

  25. public function sendToVipCustomer(VipCustomer $vip)

  26. {

  27. printf("Send email to %s[%s]", $vip->getName(), $vip->getEmail());

  28. }

  29. }

  30.  
  31. /**

  32. * 普通用户

  33. */

  34. class CommonCustomer

  35. {

  36. private $name;

  37. private $email;

  38.  
  39. public function __construct(string $name, string $email)

  40. {

  41. $this->name = $name;

  42. $this->email = $email;

  43. }

  44.  
  45. public function getName()

  46. {

  47. return $this->name;

  48. }

  49.  
  50. public function getEmail()

  51. {

  52. return $this->email;

  53. }

  54. }

  55.  
  56. /**

  57. * Vip 用户

  58. */

  59. class VipCustomer

  60. {

  61. private $name;

  62. private $email;

  63.  
  64. public function __construct(string $name, string $email)

  65. {

  66. $this->name = $name;

  67. $this->email = $email;

  68. }

  69.  
  70. public function getName()

  71. {

  72. return $this->name;

  73. }

  74.  
  75. public function getEmail()

  76. {

  77. return $this->email;

  78. }

  79. }

  80.  
  81. $customer = new CommonCustomer("liugongzi", "liuqing_hu@126.com");

  82. $vip = new VipCustomer("vip", "liuqing_hu@126.com");

  83.  
  84. $sender = new EmailSender();

  85. $sender->sendToCommonCustomer($customer);// Send email to liugongzi[liuqing_hu@126.com]

  86. $sender->sendToVipCustomer($vip);// Send email to vip[liuqing_hu@126.com]

这里,为了演示说明我们通过在 EmailSender 类中的 send* 方法中使用类型提示功能,对接收参数进行限制。所以如果有多个用户类型可能就需要实现多个 send 方法才行。

依据 里氏替换原则 我们知道,能够接收父类的地方 一定 能够接收子类作为参数。所以我们仅需定义 send 方法来接收父类即可实现不同类型用户的邮件发送功能:

 
  1. <?php

  2.  
  3. /**

  4. * 发送邮件

  5. */

  6. class EmailSender

  7. {

  8. /**

  9. * 发送邮件给普通用户

  10. *

  11. * @param CommonCustomer $customer

  12. * @return void

  13. */

  14. public function send(Customer $customer)

  15. {

  16. printf("Send email to %s[%s]", $customer->getName(), $customer->getEmail());

  17. }

  18. }

  19.  
  20. /**

  21. * 用户抽象类

  22. */

  23. abstract class Customer

  24. {

  25. private $name;

  26. private $email;

  27.  
  28. public function __construct(string $name, string $email)

  29. {

  30. $this->name = $name;

  31. $this->email = $email;

  32. }

  33.  
  34. public function getName()

  35. {

  36. return $this->name;

  37. }

  38.  
  39. public function getEmail()

  40. {

  41. return $this->email;

  42. }

  43.  
  44. }

  45.  
  46. /**

  47. * 普通用户

  48. */

  49. class CommonCustomer extends Customer

  50. {

  51. }

  52.  
  53. /**

  54. * Vip 用户

  55. */

  56. class VipCustomer extends Customer

  57. {

  58. }

  59.  
  60. $customer = new CommonCustomer("liugongzi", "liuqing_hu@126.com");

  61. $vip = new VipCustomer("vip", "liuqing_hu@126.com");

  62.  
  63. $sender = new EmailSender();

  64. $sender->send($customer);// Send email to liugongzi[liuqing_hu@126.com]

  65. $sender->send($vip);// Send email to vip[liuqing_hu@126.com]

修改后的 send 方法接收 Customer 抽象类作为参数,到实际运行时传入具体实现类就可以轻松扩展需求,再多客户类型也不用担心了。

依赖倒置原则(Dependence Inversion Principle[DIP]) ★★★★★

依赖倒转原则:抽象不应该依赖于细节,细节应当依赖于抽象。换言之,要针对接口编程,而不是针对实现编程。

在里氏替换原则中我们在未进行优化的代码中将 CommonCustomer 类实例作为 sendToCommonCustomer 的参数,来实现发送用户邮件的业务逻辑,这里就违反了「依赖倒置原则」。

如果想在模块中实现符合依赖倒置原则的设计,要将依赖的组件抽象成更高层的抽象类(接口)如前面的 Customer 类,然后通过采用 依赖注入(Dependency Injection) 的方式将具体实现注入到模块中。另外,就是要确保该原则的正确应用,实现类应当仅实现在抽象类或接口中声明的方法,否则可能造成无法调用到实现类新增方法的问题。

这里提到「依赖注入」设计模式,简单来说就是将系统的依赖有硬编码方式,转换成通过采用 设值注入(setter)构造函数注入 和 接口注入 这三种方式设置到被依赖的系统中,感兴趣的朋友可以阅读我写的 深入浅出依赖注入 一文。

举例,我们的用户在登录完成后需要通过缓存服务来缓存用户数据:

 
  1. <?php

  2.  
  3. class MemcachedCache

  4. {

  5. public function set($key, $value)

  6. {

  7. printf ("%s for key %s has cached.", $key, json_encode($value));

  8. }

  9. }

  10.  
  11. class User

  12. {

  13. private $cache;

  14.  
  15. /**

  16. * User 依赖于 MemcachedCache 服务(或者说组件)

  17. */

  18. public function __construct()

  19. {

  20. $this->cache = new MemcachedCache();

  21. }

  22.  
  23. public function login()

  24. {

  25. $user = ['id' => 1, 'name' => 'liugongzi'];

  26. $this->cache->set('dp:uid:' . $user['id'], $user);

  27. }

  28. }

  29.  
  30. $user = new User();

  31. $user->login(); // dp:uid:1 for key {"id":1,"name":"liugongzi"} has cached.

这里,我们的缓存依赖于 MemcachedCache 缓存服务。然而由于业务的需要,我们需要缓存服务有 Memacached 迁移到 Redis 服务。当然,现有代码中我们就无法在不修改 User 类的构造函数的情况下轻松完成缓存服务的迁移工作。

那么,我们可以通过使用 依赖注入 的方式,来实现依赖倒置原则:

 
  1. <?php

  2.  
  3. class Cache

  4. {

  5. public function set($key, $value)

  6. {

  7. printf ("%s for key %s has cached.", $key, json_encode($value));

  8. }

  9. }

  10.  
  11. class RedisCache extends Cache

  12. {

  13. }

  14.  
  15. class MemcachedCache extends Cache

  16. {

  17. }

  18.  
  19. class User

  20. {

  21. private $cache;

  22.  
  23. /**

  24. * 构造函数注入

  25. */

  26. public function __construct(Cache $cache)

  27. {

  28. $this->cache = $cache;

  29. }

  30.  
  31. /**

  32. * 设值注入

  33. */

  34. public function setCache(Cache $cache)

  35. {

  36. $this->cache = $cache;

  37. }

  38.  
  39. public function login()

  40. {

  41. $user = ['id' => 1, 'name' => 'liugongzi'];

  42. $this->cache->set('dp:uid:' . $user['id'], $user);

  43. }

  44. }

  45.  
  46. // use MemcachedCache

  47. $user = new User(new MemcachedCache());

  48. $user->login(); // dp:uid:1 for key {"id":1,"name":"liugongzi"} has cached.

  49.  
  50. // use RedisCache

  51. $user->setCache(new RedisCache());

  52. $user->login(); // dp:uid:1 for key {"id":1,"name":"liugongzi"} has cached.

完美!

接口隔离原则(Interface Segregation Principle[ISP]) ★★

接口隔离原则:使用多个专门的接口,而不使用单一的总接口,即客户端不应该依赖那些它不需要的接口。

简单来说就是不要让一个接口来做太多的事情。比如我们定义了一个 VipDataDisplay 接口来完成如下功能:

  • 通过 readUsers 方法读取用户数据;
  • 可以使用 transformToXml 方法将用户记录转存为 XML 文件;
  • 通过 createChart 和 displayChart 方法完成创建图表及显示;
  • 还可以通过 createReport 和 displayReport 创建文字报表及现实。
 
  1. abstract class VipDataDisplay

  2. {

  3. public function readUsers()

  4. {

  5. echo 'Read all users.';

  6. }

  7.  
  8. public function transformToXml()

  9. {

  10. echo 'save user to xml file.';

  11. }

  12.  
  13. public function createChart()

  14. {

  15. echo 'create user chart.';

  16. }

  17.  
  18. public function displayChart()

  19. {

  20. echo 'display user chart.';

  21. }

  22.  
  23. public function createReport()

  24. {

  25. echo 'create user report.';

  26. }

  27.  
  28. public function displayReport()

  29. {

  30. echo 'display user report.';

  31.  
  32. }

  33. }

  34.  
  35. class CommonCustomerDataDisplay extends VipDataDisplay

  36. {

  37.  
  38. }

现在我们的普通用户 CommonCustomerDataDisplay 不需要 Vip 用户这么复杂的展现形式,仅需要进行图表显示即可,但是如果继承 VipDataDisplay 类就意味着继承抽象类中所有方法。

现在我们将 VipDataDisplay 抽象类进行拆分,封装进不同的接口中:

 
  1. interface ReaderHandler

  2. {

  3. public function readUsers();

  4. }

  5.  
  6. interface XmlTransformer

  7. {

  8. public function transformToXml();

  9. }

  10.  
  11. interface ChartHandler

  12. {

  13. public function createChart();

  14.  
  15. public function displayChart();

  16. }

  17.  
  18. interface ReportHandler

  19. {

  20. public function createReport();

  21.  
  22. public function displayReport();

  23. }

  24.  
  25. class CommonCustomerDataDisplay implements ReaderHandler, ChartHandler

  26. {

  27. public function readUsers()

  28. {

  29. echo 'Read all users.';

  30. }

  31.  
  32. public function createReport()

  33. {

  34. echo 'create user report.';

  35. }

  36.  
  37. public function displayReport()

  38. {

  39. echo 'display user report.';

  40.  
  41. }

  42. }

重构完成后,仅需在实现类中实现接口中的方法即可。

合成复用原则(Composite Reuse Principle[CRP]) ★★★★

合成复用原则:尽量使用对象组合,而不是继承来达到复用的目的。

合成复用原则就是在一个新的对象里通过关联关系(包括组合和聚合)来使用一些已有的对象,使之成为新对象的一部分;新对象通过委派调用已有对象的方法达到复用功能的目的。简言之:复用时要尽量使用组合/聚合关系(关联关系) ,少用继承。

何时使用继承,何时使用组合(或聚合)?

当两个类之间的关系属于 IS-A 关系时,如 dog is animal,使用 继承;而如果两个类之间属于 HAS-A 关系,如 engineer has a computer,则优先选择组合(或聚合)设计。

示例,我们的系统有用日志(Logger)功能,然后我们实现了向控制台输入日志(SimpleLogger)和向文件写入日志(FileLogger)两种实现:

 
  1. <?php

  2.  
  3. abstract class Logger

  4. {

  5. abstract public function write($log);

  6. }

  7.  
  8. class SimpleLogger extends Logger

  9. {

  10. public function write($log)

  11. {

  12. print((string) $log);

  13. }

  14. }

  15.  
  16. class FileLogger extends Logger

  17. {

  18. public function write($log)

  19. {

  20. file_put_contents('logger.log', (string) $log);

  21. }

  22. }

  23.  
  24. $log = "This is a log.";

  25.  
  26. $sl = new SimpleLogger();

  27. $sl->write($log);// This is a log.

  28.  
  29. $fl = new FileLogger();

  30. $fl->write($log);

看起来很好,我们的简单日志和文件日志能够按照我们预定的结果输出和写入文件。很快,我们的日志需求有了写增强,现在我们需要将日志同时向控制台和文件中写入。有几种解决方案吧:

  • 重新定义一个子类去同时写入控制台和文件,但这似乎没有用上我们已经定义好的两个实现类:SimpleLogger 和 FileLogger;
  • 去继承其中的一个类,然后实现另外一个类的方法。比如继承 SimpleLogger,然后实现写入文件日志的方法;嗯,没办法 PHP 是单继承的语言;
  • 使用组合模式,将 SimpleLogger 和 FileLogger 聚合起来使用。

我们直接看最后一种解决方案吧,前两种实在是有点。

 
  1. class AggregateLogger

  2. {

  3. /**

  4. * 日志对象池

  5. */

  6. private $loggers = [];

  7.  
  8. public function addLogger(Logger $logger)

  9. {

  10. $hash = spl_object_hash($logger);

  11. $this->loggers[$hash] = $logger;

  12. }

  13.  
  14. public function write($log)

  15. {

  16. array_map(function ($logger) use ($log) {

  17. $logger->write($log);

  18. }, $this->loggers);

  19. }

  20. }

  21.  
  22. $log = "This is a log.";

  23.  
  24. $aggregate = new AggregateLogger();

  25.  
  26. $aggregate->addLogger(new SimpleLogger());// 加入简单日志 SimpleLogger

  27. $aggregate->addLogger(new FileLogger());// 键入文件日志 FileLogger

  28.  
  29. $aggregate->write($log);

可以看出,采用聚合的方式我们可以非常轻松的实现复用。

迪米特法则

设计模式六大原则(5):迪米特法则

感谢 Liuwei-Sunny 大神在「软件架构、设计模式、重构、UML 和 OOAD」领域的分享,才有此文。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值