软件设计七大原则之依赖倒置原则

依赖倒置原则

核心思想是:要面向接口编程,不要面向实现编程。

例1:顾客购物程序。

分析,顾客购物从然后从成都商店和兰州商店购物。uml图如下
在这里插入图片描述

1.顾客会从很多家商店购物,抽象一个商店接口,

public interface Shop {
    void sell();
}

2.兰州与成都商店实现shop购买方式

public class ChengduShop implements Shop {
    @Override
    public void sell() {
        System.out.println("购买成都店特产:火锅");
    }
}

public class LanZhouShop implements Shop {
    @Override
    public void sell() {
        System.out.println("购买兰州特产:拉面");
    }
}

3.顾客购买方法

public class Custom {
    public void buy(Shop shop) {
        shop.sell();
    }
}

4.实现

Custom custom = new Custom();
// 买兰州特产
custom.buy(new LanZhouShop());
// 买成都特产
custom.buy(new ChengduShop());

例2 学生学习课程(java,c++。。。)
UML图如下
在这里插入图片描述

1.抽象课程的学习动作。

public interface Course {
    void study();
}

2.两种课程实现course

public class JavaCourse implements Course {
    @Override
    public void study() {
        System.out.println("学习java课程");
    }
}
public class CplusCourse implements Course {
    @Override
    public void study() {
        System.out.println("学习c++课程");
    }
}

3.学生学习课程的方法

public class Student {
    /**
     * 依赖注入
     * @param course
     */
   public void study(Course course){
       course.study();
   }
   }

4.实现

Student student = new Student();
student.study(new JavaCourse());
student.study(new CplusCourse());

此时的注入方式的通过依赖注入,还有两种注入方式,分别是构造注入(通过构造方法)与set注入(通过set方法–如果是单例只能通过这钟fangs)。

Student类

 /**
     * 课程属性
     */
    private Course course;
    public void study(){
        course.study();
    }
    /**
     * set注入
     */
   public void setCourse(Course course) {
        this.course = course;
    }

    /**
     * 构造注入
     * @param course
     */
    public Student(Course course) {
        this.course = course;
    }

实现方式

 /**
         * 构造注入
         */
        System.out.println("构造方式注入:");
        Student student = new Student(new JavaCourse());
        student.study();
        /**
         * set注入
         */
        System.out.println();
        System.out.println("set方式注入:");
        student.setCourse(new CplusCourse());
        student.study();

在这里插入图片描述
参考资料:
1.http://c.biancheng.net/view/1326.html
代码地址:https://gitee.com/zhoujie1/design-mode-and-principle.git

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值