从工厂模式到IoC控制反转(inversion of Control)简单代码的逐步实现

本文介绍了从简单的类调用到工厂模式,再到IoC(控制反转)的实现思路,通过A类和B类的例子展示了如何在B类中调用A类方法。文中提到了使用反射和配置文件来实现IoC,详细阐述了每个步骤,并在最后给出了使用properties文件加载类路径的示例,旨在帮助读者理解依赖注入的概念和应用。

今天假期xin麒继续卷。

​ 唉,每当一个人偷偷卷时,总是会默默落泪,哪个富婆又能看穿麒麒内心得脆弱,走进麒麒柔弱的心房,及时给予麒麒最及时的温柔呢?

来一波工厂模式到IoC(全称inversion of control)实现思路的简单分析:

一、前提引入:

  • 有A类和B类,xin麒想在B类中一个方法实现A类的调用,应该如何实现才更好呢?

二、实现

从历史演变的过程应该是这样子的:

1、最初始的思路:

​ 首先在两个java分别定义A类和B类,B类直接在那个方法中创建并且调用A类方法。

实现以上思路:

public class A {
    public void aMethod(){
        System.out.println("the method named \"aMethod\" in" +
                " the class of A had been use");

    }
}
public class B {
    public static void main(String[] args) {
        bMethod();
    }
    public static void bMethod(){
        A a = new A();
        a.aMethod();
    }
}

运行:

在这里插入图片描述

2、工厂模式:

B类方法不再是独自地实现调用A类的方法了,因为B类方法中经过了富婆C类的帮助:

​ 就是C类的一个静态方法实现A类的创建,曾经孤单的B类方法经过富婆C的帮助实现A类的创建。

实现思路:

public class A {
    public void aMethod(){
        System.out.println("the method named \"aMethod\" in" +
                " the class of A had been use");

    }
}
public class C {
    public static A GetAClass(){
        return new A();

    }
}

public class B {
    public static void main(String[] args) {
        bMethodHelpedByC();
    }
    public static void bMethodHelpedByC(){
        A a = C.GetAClass();
        a.aMethod();
    }
}

运行:

在这里插入图片描述

三、IoC

实际上,是使用到了反射+工厂模式的思路:

代码文件路径:

在这里插入图片描述

具体实现:

public class A {
    public void aMethod(){
        System.out.println("the method named \"aMethod\" in" +
                " the class of A had been use");
    }
}
public class C {
    public static A GetAClassByreflex() throws Exception {
        Class<?> aClass = Class.forName("com.lws.personaltest.FactoryPattern.A");
        return (A)aClass.newInstance();
    }
}

public class B {
    public static void main(String[] args) throws Exception {
        bMethodHelpedByC2();
    }
    public static void bMethodHelpedByC2() throws Exception {
        A a = C.GetAClassByreflex();
        a.aMethod();
    }
}

运行:

在这里插入图片描述

外加一个配置文件,如果回到java基础,我们可以使用properties文件,当然,在java项目中可能会使用其他的配置文件.这里xin麒还记得properties,那就使用properties来演示吧。

主要思路:

  • 在properties文件编写A类的路径
  • 通过输入流load到properties对象;
  • C类的静态方法通过properties对象获取A类的路径的String型变量;
        • 通过Class.forName()反射获取class类对象的变量aClass
  • 通过变量aClass创建一个实例对象返回。

文件路径介绍:

在这里插入图片描述

具体实现:

public class A {
    public void aMethod(){
        System.out.println("the method named \"aMethod\" in" +
                " the class of A had been use");
    }
}
public class C {
    public static A GetAClassByreflexAndProperties() throws Exception {
        FileInputStream fileInputStream = new FileInputStream("src\\NameOfClassA.properties");
        Properties properties = new Properties();
        properties.load(fileInputStream);
        String strClassA = properties.get("ClassA").toString();
        Class<?> aClass = Class.forName(strClassA);
        return (A)aClass.newInstance();
    }
}

public class B {
    public static void main(String[] args) throws Exception {
        bMethodHelpedByC3();
    }
    public static void bMethodHelpedByC3() throws Exception {
        System.out.println("通过了GetAClassByreflexAndProperties 方法");
        A a = C.GetAClassByreflexAndProperties();
        a.aMethod();
    }
}

运行:

在这里插入图片描述

xin麒如有不足,希望大家指正!!!
end.

IOCInversion of Control控制反转中,对象创建与传统开发模式有显著不同。传统开发模式里,对象的创建和依赖关系由代码自身管理和实现;而在 IOC 模式下,对象的创建和依赖关系由外部容器负责,这种控制的反转降低了组件之间的耦合度,提高了代码的可维护性和可测试性[^1]。 以 Spring 框架为例,它提供了一种 IOC 容器来控制对象的创建。无论是对象的创建、处理对象之间的依赖关系、对象的创建时间,还是对象的创建数量,都只需在 Spring 提供的 IOC 容器上配置对象的信息即可[^5]。 IOC 实现对象创建常见的方式有依赖注入(Dependency Injection,简称 DI)和依赖查找(Dependency Lookup),其中依赖注入最为常见。在依赖注入中,又可通过构造器进行注入对象和使用 setter 方法进行注入等具体方式来实现对象创建及依赖关系的处理[^3][^4]。 ### 示例代码 以下是一个简单使用 Spring 框架的 IOC 进行对象创建和依赖注入的示例(基于 JavaSpring 框架): ```java import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; // 定义一个接口 interface MessageService { String getMessage(); } // 实现接口 class EmailService implements MessageService { @Override public String getMessage() { return "This is an email message."; } } // 定义一个需要依赖 MessageService 的类 class MessagePrinter { private MessageService service; // 构造器注入 public MessagePrinter(MessageService service) { this.service = service; } public void printMessage() { System.out.println(service.getMessage()); } } public class Main { public static void main(String[] args) { // 加载 Spring 配置文件 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // 从 IOC 容器中获取对象 MessagePrinter printer = context.getBean("messagePrinter", MessagePrinter.class); // 调用方法 printer.printMessage(); } } ``` ### applicationContext.xml 配置文件示例 ```xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 定义 MessageService 实现类的 Bean --> <bean id="emailService" class="com.example.EmailService"/> <!-- 定义 MessagePrinter Bean,并通过构造器注入依赖 --> <bean id="messagePrinter" class="com.example.MessagePrinter"> <constructor-arg ref="emailService"/> </bean> </beans> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值