zoukankan      html  css  js  c++  java
  • spring——IOC理论

    这里主要是对于IOC理论提出的一个认识

    1. dao接口

      public interface Fruit {
          String getFruit();
      }
      
    2. dao接口的实现类

      public class FruitImpl implements Fruit {
          public String getFruit() {
              return "Buy Some fruit";
          }
      }
      
    3. 服务层接口

      public interface UserService {
          String buyFruit();
      }
      
    4. 服务层实现类

      public class UserServiceImpl implements UserService{
          Fruit fruit;
      
          public UserServiceImpl() {
              fruit = new FruitImpl();
          }
      
          public String buyFruit() {
              return fruit.getFruit();
          }
      }
      
    5. 测试:

      public static void main(String[] args) {
          UserServiceImpl userService = new UserServiceImpl();
          System.out.println(userService.buyFruit());
      }
      //输出:Buy Some fruit
      
    6. 新需求:

      注:以买水果为例(之前在知乎看到的示例),在service层的实现类中,由程序员选择特定的商品Fruit交给客户,但是这样一来,如果遇到特殊的需求(比如要更换购买的水果,比如香蕉,苹果…),我们需要另外写dao层的接口实现类.

      public class Aplle implements Fruit {
          public String getFruit() {
              return "Buy some Applle";
          }
      }
      
    7. 控制权反转(IOC):

      同时还要修改service层的实现类,显然这不是一个好的实现方法.让我们做个小小的改变——在服务层的实现类中增加一个set方法,使客户能够主动"挑选水果":

      public static void main(String[] args) {
          UserServiceImpl userService = new UserServiceImpl();
          userService.setFruit(new Apple());
          System.out.println(userService.buyFruit());
      }
      

    注:psvm -> 当前类的main函数

    理解:程序主动创建对象,控制权在程序员手上 -> "客户创建对象",程序被动接收对象

    好处:程序员不用再去管理对象的创建,系统耦合性大大降低,可以专注与业务层

    实现:set方法

    根本目的:解耦

    本质:控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现 控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)

  • 相关阅读:
    173. Binary Search Tree Iterator
    199. Binary Tree Right Side View
    230. Kth Smallest Element in a BST
    236. Lowest Common Ancestor of a Binary Tree
    337. House Robber III
    449. Serialize and Deserialize BST
    508. Most Frequent Subtree Sum
    513. Find Bottom Left Tree Value
    129. Sum Root to Leaf Numbers
    652. Find Duplicate Subtrees
  • 原文地址:https://www.cnblogs.com/Arno-vc/p/13387064.html
Copyright © 2011-2022 走看看