微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

设计原则之单一职能原则

设计原则之单一职能原则

动机:
一个职能被考虑成为只有唯一理由去改变,如果我们有两个理由去改变一个类,我们要把这两个功能分成两个类。每个类只控制一个职能,如果在未来有一天我们做某个改变,去改变对应的类就行了。
目标:一个类应该只有一个被改的理由。

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;}
}

原文地址:https://www.jb51.cc/javaschema/283501.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐