您当前的位置: 首页 > 

java持续实践

暂无认证

  • 2浏览

    0关注

    746博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

设计模式 依赖倒置原则

java持续实践 发布时间:2022-03-13 10:23:51 ,浏览量:2

文章目录
      • 依赖倒置原则
      • 依赖倒置原则实战
        • 使用依赖倒置原则进行改变
        • 案例中两种方式的类图

依赖倒置原则

定义: 程序要依赖于抽象接口, 不要依赖于具体实现, 对抽象进行编程, 而不是对实现进行编程, 降低了客户与实现模块的耦合. 高层模块不应该依赖底层模块, 都应该依赖抽象(接口 抽象类)

上级找下级, 一般不会直接找你 ,而是通过助理等找到. 下级去依赖上级的标准等. 上级出的标准, 不需要去关心下级如何去实现的. 降低上级的耦合性. spring的spi机制等.

依赖倒置原则实战

随机抽奖与权重抽奖. 不使用依赖倒置原则的写法 : 定义抽奖用户类

public class BetUser {

    private String userName;
    // 权重
    private int userWeight;

    public BetUser() {
    }

    public BetUser(String userName, int userWeight) {
        this.userName = userName;
        this.userWeight = userWeight;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getUserWeight() {
        return userWeight;
    }

    public void setUserWeight(int userWeight) {
        this.userWeight = userWeight;
    }
}

抽奖控制类, 在抽奖控制类中, 分别实现了随机抽奖, 和根据权重排序抽奖的方法.

public class DrawControl {
    
    /**
     // 随机抽奖
     * @param list  抽奖的人集合
     * @param count 中奖人数
     * @return
     */
    public List doDrawRandom(List list, int count) {
        if (list.size()  0 ? 1 : -1;
        });
        // 取出指定数量的中奖用户
        List prizeList = new ArrayList(count);
        for (int i = 0; i             
关注
打赏
1658054974
查看更多评论
0.0405s