mynotes/编程思想/写代码的思想习惯.md
2019-10-17 11:40:32 +08:00

1.5 KiB
Raw Permalink Blame History

写代码的思想习惯

  1. 考虑代码的通用性,不需要更改里面的代码,可以让很多情况都可以调用

    • 将需要更改的信息写在配置文件里,代码中只需要读取配置文件,并用接口接收读取的值;

      public Connection getConnection() throws Exception {
          //	从本地加载配置文件到输入流
          InputStream input = getClass().getResourceAsStream("jdbc.properties");
      	//	将数据流加载到对象info中
          Properties info = new Properties();
          info.load(input);
      	//	读取具体配置数据
          String className = info.getProperty("driver");
          String url = info.getProperty("url");
          String user = info.getProperty("user");
          String password = info.getProperty("password");
      	//	通过反射利用配置数据将接口Driver实例化
          Driver driver = (Driver) Class.forName(className).newInstance();
      	//	利用实例化后的接口进行业务逻辑操作
          info = new Properties();
          info.put("user",user);
          info.put("password",password);
          Connection connect = driver.connect(url, info);
      
          return connect;
      }
      
      • 这样,编译期间并不知道接口被哪个实例实现;当程序运行的时候,读取配置文件后,才知道接口被谁实现。
      • 只需要更改配置文件,就可以控制接口的实例对象,不需要更改代码。