栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【体系结构(设计模式)】单一职责原则

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【体系结构(设计模式)】单一职责原则

概念
一个类应该只负责一项职责。
如果类A负责两个不同职责:职责1、职责2,当职责1需求变更而改变A时,可能造成职责2执行错误,所以需要将A的粒度分解为A1、A2

注意事项和细节

1、降低类的复杂度,一个类只负责一项职责

2、提高类的可读性、可维护性

3、降低变更引起的风险

4、逻辑足够简单,可以在代码级别违反单一职责SingleResponsibility1;
方法数量足够少,可以在方法级别保持单一职责SingleResponsibility2

package com.atguigu.principle.singleresponsibility;

public class SingleResponsibility1 {

    public static void main(String[] args){
        Vehicle vehicle = new Vehicle();
        vehicle.run("摩托车");
        vehicle.run("汽车");
        vehicle.run("飞机");
    }

}

//交通工具类


class Vehicle{
    public void run(String vehicle){
        System.out.println(vehicle + "在公路上……");
    }
}
package com.atguigu.principle.singleresponsibility;

public class SingleResponsibility2 {
    public static void main(String[] args) {
        RoadVehicle roadvehicle = new RoadVehicle();
        roadvehicle.run("摩托车");
        AirVehicle airVehicle = new AirVehicle();
        airVehicle.run("飞机");

    }
}


class RoadVehicle{
    public void run(String vehicle){
        System.out.println(vehicle + "在公路上……");
    }
}
class AirVehicle{
    public void run(String vehicle){
        System.out.println(vehicle + "在空中……");
    }
}
class WaterVehicle{
    public void run(String vehicle){
        System.out.println(vehicle + "在水里……");
    }
}
package com.atguigu.principle.singleresponsibility;

public class SingleResponsibility3 {
    public static void main(String[] args) {
        Vehicle2 vehicle = new Vehicle2();
        vehicle.run("摩托车");
        vehicle.run("汽车");
        vehicle.runAir("飞机");
    }
}


class Vehicle2{
    public void run(String vehicle){
        System.out.println(vehicle + "在公路上……");
    }
    public void runAir(String vehicle){
        System.out.println(vehicle + "在空中……");
    }
    public void runWater(String vehicle){
        System.out.println(vehicle + "在水里……");
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/309621.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号