前端之家收集整理的这篇文章主要介绍了
设计原则之单一职能原则,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
- 设计原则之单一职能原则
-
- 动机:
- 一个职能被考虑成为只有唯一理由去改变,如果我们有两个理由去改变一个类,我们要把这两个功能分成两个类。每个类只控制一个职能,如果在未来有一天我们做某个改变,去改变对应的类就行了。
- 目标:一个类应该只有一个被改的理由。
-
- BadExample:缺点:
- 1、新增一个新的协议将会带来一个新需求,要为每种域序列化内容。
- 2、内容不一定是string,也会有html等其他形式。
-
- //singleresponsibilityprinciple-badexample
- interfaceIEmail{
- publicvoidsetSender(Stringsender);
- publicvoidsetReceiver(Stringreceiver);
- publicvoidsetContent(Stringcontent);
- }
- classEmailimplementsIEmail{
- publicvoidsetSender(Stringsender){//setsender;}
- publicvoidsetReceiver(Stringreceiver){//setreceiver;}
- publicvoidsetContent(Stringcontent){//setcontent;}
- }
- GoodExample:好处:
- 1、新增一个新的协议只要改email类
- 2、一个新的content只要修改content类。
- //singleresponsibilityprinciple-goodexample
- interfaceIEmail{
- publicvoidsetSender(Stringsender);
- publicvoidsetReceiver(Stringreceiver);
- publicvoidsetContent(IContentcontent);
- }
- interfaceContent{
- publicStringgetAsString();//usedforserialization
- }
- classEmailimplementsIEmail{
- publicvoidsetSender(Stringsender){//setsender;}
- publicvoidsetReceiver(Stringreceiver){//setreceiver;}
- publicvoidsetContent(IContentcontent){//setcontent;}
- }