new与反射、面向接口、properties和xml配置、控制反转与依赖注入的理解

本文探讨了Java中面向接口编程的优势,展示了如何通过修改配置文件来切换不同的实现类,而不需改动源码。同时,介绍了Java中对象生成的两种方式:new与反射,并比较了properties与xml作为配置文件的形式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • java中产生对象的两种方式:new与反射
  • java中配置文件形式:properites与xml
  • 面向接口的好处:不满意原来的实现方式时,可以写一个新的实现类,只改动配置文件,无需改动源码

这里写图片描述

package com.service;

import com.entity.Student;

public interface IStudentService {

    public void addStudent(Student s);

}
package com.service;

import com.entity.Student;

public class StudentService implements IStudentService {

    @Override
    public void addStudent(Student s) {
        //实现添加一个学生的业务,实现类1,例如用时:10秒
        System.out.println("IStudentService接口实现类1"+":用时10秒");
    }

}
package com.service;

import com.entity.Student;

public class StudentService2 implements IStudentService {

    @Override
    public void addStudent(Student s) {
        //实现添加一个学生的业务,实现类2,例如用时:1秒
        System.out.println("IStudentService接口实现类2"+":用时1秒");
    }

}
package com.test;
import java.util.Properties;

import com.entity.Student;
import com.service.IStudentService;

public class Demo1 {

    /**
     * @param args
     * @throws ClassNotFoundException 
     * @throws IllegalAccessException 
     * @throws InstantiationException 
     */
    public static void main(String[] args) throws Exception {
        //产生对象的两种方式
        //第一种,new
        Student s1 = new Student();
        s1.setName("张三");
        System.out.println(s1.getName());

        //第二种,反射
        Student s2 = (Student) Class.forName("com.entity.Student").newInstance();
        s2.setName("李四");
        System.out.println(s2.getName());

        //为什么要面向接口编程?
        //IStudentService service = (IStudentService) Class.forName("com.service.StudentService").newInstance();
        //service.addStudent(null);
        //当我对IStudentService的第一个实现类的效率不满意时,我启用第二个实现类,只用改动反射中forName里的字符串参数,在代码里改动了一处,如:
        //IStudentService service = (IStudentService) Class.forName("com.service.StudentService2").newInstance();
        //service.addStudent(null);
        //我如果将forName里的字符串信息写到外部的.properties简单配置文件中,则以后换实现方式,只需改配置文件,而无需改动源码,好处即在此,如:
        Properties pro = new Properties();
        pro.load(Demo1.class.getResourceAsStream("object.properties"));
        IStudentService service = (IStudentService) Class.forName(pro.getProperty("name")).newInstance();
        service.addStudent(null);
        //后面学到Spring里的IoC/DI,反射被Spring容器自动实现了,它用的配置文件不是简单的.properties,而是xml
        //为什么用xml呢?因为xml文档结构适用于更复杂的配置,通过xml及工厂反射模式,spring还实现了对象注入

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值