本帖最后由 丁二跃 于 2012-7-8 21:13 编辑
其实在那个例子中你就可以看到好处了:
这里你把ips 定义为Inputstream
在第一种方法加载配置文件时 ips=new FileInputStream("config.properties");
利用第二种方法时仍旧可以: ips= PropertiesTest.class.getClassLoader().getSystemResourceAsStream("config2.properties");
同样第三种方法仍可以。
如果你把它定义成FileInputStream 那么当你修改程序时,不是还要改ips 类型吗
这里还不能体现面向接口的好处。看一下工厂模式吧,讲的很详细……看过你就知道
写了个简单的:- public class Test {
- public static void main(String[] args) throws Exception{
- Meth m=MethFactory.getMeth(); //面向接口,工厂类提供实例对象。
- m.dis();
- }
- }
- //该方法用于获得 实现 接口的实例
- class MethFactory{
- static Meth getMeth()throws Exception{
- Properties properties=new Properties();
- properties.load(
- MethFactory.class.getClassLoader().getSystemResourceAsStream("config2.properties"));
- return (Meth) Class.forName((String)properties.getProperty("className")).newInstance();
- }
- }
- interface Meth{ //定义接口
- void dis();
- }
- class ImplA implements Meth{
- public void dis() {
- System.out.println("接口实现 A");
- }
- }
- class ImplB implements Meth{
- public void dis() {
- System.out.println("接口实现 B");
- }
- }
复制代码 配置文件:className=cn.ref.day35.ImplA
现在需要改变一种实现方式,只需要修改配置文件即可className=cn.ref.day35.ImplB 而不用去管源程序。
这就是面向接口的好处了……降低而耦合度,增加可维护性
|