面向对象的7种设计原则(1)-单一职责原则

永远不要让一个类存在多个改变的理由。

单一原则表明,如果你有多个原因去改变一个类,那么应该把这些引起变化的原因分离开,把这个类分成多个类,每个类只负责处理一种改变。当你做出某种改变时,只需要修改负责处理该改变的类。当我们去改变一个具有多个职责的类时可能会影响该类的其他功能

单一职责原则代表了设计应用程序时一种很好的识别类的方式,并且它提醒你思考一个类的所有演化方式。只有对应用程序的工作方式有了很好的理解,才能很好的分离职责。

单一职责原则原则的核心含意是:只能让一个类/接口/方法有且仅有一个职责。

案例:

public class Animal {
    public void run(String animal){
        System.out.println(animal+"running on the land...");
    }
     public static void main(String[] args) {
        Animal animal = new Animal();
        animal.run("狗");
        animal.run("牛");
        animal.run("马");
    }
}

运行结果:

狗running on the land...
牛running on the land...
马running on the land...

然而并不是所有的动物都在陆地上奔跑,鸟在天上飞,鱼在水中游。这时的Animal类就不符合单一职责,需要将Animal进行细分。

第一种:

    class Aquatic{
        public void run(String animal){
            System.out.println(animal+"swimming in the water...");
        }
    }

    class Terrestrial{
        public void run(String animal){
            System.out.println(animal+"running on the land...");
        }
    }

    class Birds{
        public void run(String animal){
            System.out.println(animal+"flying in the sky...");
        }
    }

第二种:

这种修改方式直接在代码级别上违背了单一职责原则,虽然修改起来最简单,但隐患却是最大的。

public class Animal {

    public void run(String animal){
        if("fish".equals(animal)){
            System.out.println(animal+"swimming in the water...");
        }else if("bird".equals(animal)){
            System.out.println(animal+"flying in the sky...");
        }else{
            System.out.println(animal+"running on land...");
        }
    }
}

第三种:

这种修改方式没有改动原来的方法,而是在类中新加了一个方法,这样虽然也违背了单一职责原则,但在方法级别上却是符合单一职责原则的,因为它并没有动原来方法的代码。

public class Animal {

    public void run1(String animal){
            System.out.println(animal+"running on land...");
    }
    
    public void run2(String animal){
        System.out.println(animal+"flying in the sky...");
    }
    
    public void run3(String animal){
        System.out.println(animal+"swimming in the water...");
    }
}

单一职责原则虽然它是最简单但又最难运用的原则,需要设计人员发现类的不同职责并将其分离,而发现类的多重职责需要设计人员具有较强的分析设计能力和相关实践经验。

个人博客
腾讯云社区
掘金
CSDN
简书
GitHub
码云
OSCHINA
Segmentfault
公众号:wx.jpg

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值