设计原则之单一职能原则
发布时间:2020-12-14 02:01:32 所属栏目:百科 来源:网络整理
导读:设计原则之单一职能原则动机:一个职能被考虑成为只有唯一理由去改变,如果我们有两个理由去改变一个类,我们要把这两个功能分成两个类。每个类只控制一个职能,如果在未来有一天我们做某个改变,去改变对应的类就行了。目标:一个类应该只有一个被改的理由
设计原则之单一职能原则 动机: 一个职能被考虑成为只有唯一理由去改变,如果我们有两个理由去改变一个类,我们要把这两个功能分成两个类。每个类只控制一个职能,如果在未来有一天我们做某个改变,去改变对应的类就行了。 目标:一个类应该只有一个被改的理由。 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;} } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |