对类来说的,即一个类应该只负责一项职责。如类A负责两个不同的职责,职责1,职责2。当职责1需求变更而改变A时,可能造成职责2智行错误,所以要将类A的粒度分解为A1,A2文章来源:https://www.toymoban.com/news/detail-618794.html
错误的应用实例
package org.example.demo0; /** * @description: 单一职责原则 * @author: abel.he * @date: 2023-07-31 **/ public class SingleResponsibility { public static void main(String[] args) { Vehicle vehicle = new Vehicle(); vehicle.run("摩托车"); vehicle.run("汽车"); vehicle.run("飞机"); } } class Vehicle { public void run(String vehicleName) { System.out.println(vehicleName + "在公路上运行"); } }
正确的实例
package org.example.demo0; /** * @description: 单一职责原则(正确) * @author: abel.he * @date: 2023-07-31 **/ public class SingleResponsibilityCorrect { public static void main(String[] args) { Vehicle1 vehicle1 = new Vehicle1(); vehicle1.run("小汽车"); Air air = new Air(); air.run("飞机"); } } /** * 汽车工具类 */ class Vehicle1 { public void run(String vehicleName) { System.out.println(vehicleName + "在地上跑"); } } class Air { public void run(String airName) { System.out.println(airName + "在天上飞"); } }
文章来源地址https://www.toymoban.com/news/detail-618794.html
到了这里,关于设计模式原则之:单一职责模式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!