设计模式(1)

设计模式的作用

  1. 代码重用性

  2. 可读性

  3. 可扩展性

  4. 可靠性

  5. 使程序呈现高内聚,低耦合的特性

设计模式常用的七大原则有

  1. 单一职责原则

  2. 接口隔离原则

  3. 依赖倒转原则

  4. 里式替换原则

  5. 开闭原则OCP

  6. 迪米特法则

  7. 合成复用原则

单一职责原则

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

  • 降低类的复杂度,一个只负责项职。

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

  • 降低变更引起的风险

  • 通常情况下,我们应当遵守单一职责原则,只有逻辑足够简单才可以在代码级违 反单一职责原则;只有类中方法数量足够少,可以在级别保持单一职责

  • 案例一

public class single {
    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 + "在公路上运行!");
    }
}

​ 飞机动作与摩托和汽车不符违反了单一原则

  • 案例二
public class single2 {
    @Test
    public static void main(String[] args) {
        RoadVehicle vehicle = new RoadVehicle();
        vehicle.run("摩托车!");
        vehicle.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 + "天空上运行!");
    }
}

​ 虽然遵守单一原则但浪费资源非常繁重

  • 案例三
public class single3 {
    @Test
    public static void main(String[] args) {
        Vehicle1 vehicle = new Vehicle1();
        vehicle.run("摩托车!");
        vehicle.run("汽车!");
        vehicle.run2("飞机");
        vehicle.run3("小船");
    }
}

class Vehicle1 {
    public void run(String vehicle) {
        System.out.println(vehicle + "在公路上运行!");
    }
    public void run2(String vehicle) {
        System.out.println(vehicle + "在天空上运行!");
    }
    public void run3(String vehicle) {
        System.out.println(vehicle + "在水中翱翔!");
    }
}

​ 这种修改方法没有对原来的类做大的修改,只是增加方法,在类级别没有遵守单一原则,但在方法上遵守单一原则

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值