单一职责原则

单一职责原则

对于一个类来说,即一个类只负责一项职责 ,专心的干好这一件事,不要三心二意。 比如类A负责两个职责:职责1,职责2.但职责1的需求发生了改变的情况,而对类A进行了修改,这可能会导致职责2的执行发生了错误,那么这就是设计的时候出现了问题,这种问题是可以使用单一原则来进行处理操作的。

将类A进行拆分为A1和A2

下面以实际的代码来进行相应的案例讲解操作

一共是含有三种代码实现的方式:

方案一:
package com.yt.singleResponsibility;
​
/**
 * @program: designPattern
 * @description   这种实现的方案是含有着一定的局限性的,只是含有着一个类一个方法来
 * 实现海陆空三种方案的行驶,问题是最大的!功能不能很好的实现。
 * 可以将其进行类的拆分操作实现其相对应的功能
 * @author: YangTao
 * @create: 2024-02-20 11:20
 **/
​
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 something){
        System.out.println(something + "正在路上行驶");
    }
}

方案二:
package com.yt.singleResponsibility;
​
/**
 * @program: designPattern
 * @description 将其进行拆分,每一个类对应着一个交通工具的执行操作,以次来实现对应的功能
 *              这种是单一职责的基本实现功能操作的。是对于类当中含有着多个方法来进行实现的。
 *              每一个类含有着每一个类要干的事情。这个是非常好的
 * @author: YangTao
 * @create: 2024-02-20 11:50
 **/
public class SingleResponsibility2 {
    public static void main(String[] args) {
        RoadVehicle roadVehicle = new RoadVehicle();
        roadVehicle.run("汽车");
        SeaVehicle seaVehicle = new SeaVehicle();
        seaVehicle.run("轮船");
        airVehicle airVehicle = new airVehicle();
        airVehicle.run("飞机");
    }
}
​
class RoadVehicle{
    public void run(String something){
        System.out.println(something + "正在路上行驶");
    }
}
​
class airVehicle{
    public void run(String something){
        System.out.println(something + "正在空中飞行");
    }
}
​
​
class SeaVehicle{
    public void run(String something){
        System.out.println(something + "正在海里行驶");
    }
}

方案三:
package com.yt.singleResponsibility;
​
/**
 * @program: designPattern
 * @description     单一职责设计模式
 *                  这个是针对于类当中方法较少的情况来进行实现其功能操作的
 *                  一个类含有这多个不同的方法来对其功能进行实现操作
 * @author: YangTao
 * @create: 2024-02-20 11:54
 **/
public class SingleResponsibility3 {
    public static void main(String[] args) {
        Vehicle3 vehicle3 = new Vehicle3();
        vehicle3.roadRun("汽车");
        vehicle3.SeaRun("轮船");
        vehicle3.airRun("飞机");
    }
}
​
class Vehicle3{
    public void roadRun(String something){
        System.out.println(something + "正在路上行驶");
    }
​
    public void SeaRun(String something){
        System.out.println(something + "正在大海行驶");
    }
​
    public void airRun(String something){
        System.out.println(something + "正在空中飞行");
    }
}

单一职责的注意事项及其相应的细节操作
  • 降低类的复杂度,每一个类只是要负责一项职责

  • 提高类的可读性和可维护性

  • 降低变更引起的风险

  • 在通常的情况下我们要实现单一职责的原则,只有逻辑非常的简单的情况,我们才可能会在代码的情况下违反单一职责的原则。当类当中的方法数量非常少的情况,我们是可以在方法上来实现单一职责的原则。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值