本文从面向接口编程->工厂模式->反射机制->SpringIoC,以实例的方式描述了Human实现类与HelloWorld类的解耦过程。
/** * Human接口 */ publicinterface Human { publicvoid sayHello(String name); } /** * Chinese 实现类 */ publicclass Chinese implements Human { publicvoid sayHello(String name) { String helloWorld = "你好," + name; System.out.println(helloWorld); } } /** * English 实现类 */ publicclass English implements Human { publicvoid sayHello(String name) { String helloWorld = "Hello, " + name; System.out.println(helloWorld); } } /** * HelloWorld 类 * */ publicclass HelloWorld { publicvoid dealWith(String type, String name){//传入两个参数,分别是国籍和姓名 Human human =null; if("chinese".equals(type)){ human = new Chinese(); } elseif("english".equals(type)){ human = new English(); } human.sayHello(name); } } |
注:面向接口编程,human对象的创建需要依赖具体的实现类,因此Human的实现类(Chinese、English)与HelloWorld是耦合到一块。
/** * Human 工厂类 */ publicclass HumanFactory { public Human getHuman(String type) { if ("chinese".equals(type)) { returnnew Chinese(); } elseif("english".equals(type)){ returnnew English(); } returnnull; } } /** * HelloWorld 类 */ publicclass HelloWorld { publicvoid dealWith(String type, String name){ HumanFactory factory = new HumanFactory(); Human human = factory.getHuman(type); human.sayHello(name); } } |
注:工厂类模式,通过HumanFactory将Human实现类(Chinese、English)与HelloWorld进行了解耦和。
上节通过引入HumanFactory工厂类,实现了Human实现类(Chinese、English)与HelloWorld进行了解耦和,但是如果有新的实现类(如:Japanese)引入,HumanFactory需要做修改,本节提出改进措施。
配置文件(demo.properties): chinese=com.inspur.helloworld.Chinese english=com.inspur.helloworld.English /** * Human 工厂类 */ publicclass HumanFactory { public Human getHuman(String type) { Properties prop = new Properties(); InputStream in = getClass().getResourceAsStream("demo.properties"); String className =null; //读取配置文件,获取className try { prop.load(in); className = prop.getProperty(type).trim(); } catch (IOException e) { e.printStackTrace(); } try { Class ownerClass = Class.forName(className); return (Human)ownerClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } returnnull; } } /** * HelloWorld类 */ publicclass HelloWorld { publicvoid dealWith(String type, String name){ HumanFactory factory = new HumanFactory(); Human human = factory.getHuman(type); human.sayHello(name); } } |
|
注:改进的工厂类模式,采用Java反射机制,采用配置文件配置实现类的方式,彻底解决了增加实现类的硬编码的问题。