设计原则之单一职能原则

前端之家收集整理的这篇文章主要介绍了设计原则之单一职能原则前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. 设计原则之单一职能原则
  2.  
  3. 动机:
  4. 一个职能被考虑成为只有唯一理由去改变,如果我们有两个理由去改变一个类,我们要把这两个功能分成两个类。每个类只控制一个职能,如果在未来有一天我们做某个改变,去改变对应的类就行了。
  5. 目标:一个类应该只有一个被改的理由。
  6.  
  7. BadExample:缺点:
  8. 1、新增一个新的协议将会带来一个新需求,要为每种域序列化内容
  9. 2内容不一定是string,也会有html等其他形式。
  10.  
  11. //singleresponsibilityprinciple-badexample
  12. interfaceIEmail{
  13. publicvoidsetSender(Stringsender);
  14. publicvoidsetReceiver(Stringreceiver);
  15. publicvoidsetContent(Stringcontent);
  16. }
  17. classEmailimplementsIEmail{
  18. publicvoidsetSender(Stringsender){//setsender;}
  19. publicvoidsetReceiver(Stringreceiver){//setreceiver;}
  20. publicvoidsetContent(Stringcontent){//setcontent;}
  21. }
  22. GoodExample:好处:
  23. 1、新增一个新的协议只要改email
  24. 2、一个新的content只要修改content类。
  25. //singleresponsibilityprinciple-goodexample
  26. interfaceIEmail{
  27. publicvoidsetSender(Stringsender);
  28. publicvoidsetReceiver(Stringreceiver);
  29. publicvoidsetContent(IContentcontent);
  30. }
  31. interfaceContent{
  32. publicStringgetAsString();//usedforserialization
  33. }
  34. classEmailimplementsIEmail{
  35. publicvoidsetSender(Stringsender){//setsender;}
  36. publicvoidsetReceiver(Stringreceiver){//setreceiver;}
  37. publicvoidsetContent(IContentcontent){//setcontent;}
  38. }

猜你在找的设计模式相关文章