File : IOutputGenerator.java – 输出生成器接口
package com.zyiz.output; public interface IOutputGenerator { public void generateOutput(); }
File : CsvOutputGenerator.java – 一个CSV输出生成器用来实现IOutputGenerator接口。
package com.zyiz.output.impl; import com.zyiz.output.IOutputGenerator; public class CsvOutputGenerator implements IOutputGenerator { public void generateOutput(){ System.out.println("Csv Output Generator"); } }
File : JsonOutputGenerator.java – 一个JSON输出生成器用来实现IOutputGenerator接口。
package com.zyiz.output.impl; import com.zyiz.output.IOutputGenerator; public class JsonOutputGenerator implements IOutputGenerator { public void generateOutput(){ System.out.println("Json Output Generator"); } }
package com.zyiz.netmon; import com.zyiz.output.IOutputGenerator; import com.zyiz.output.impl.CsvOutputGenerator; public class App { public static void main( String[] args ) { IOutputGenerator output = new CsvOutputGenerator(); output.generateOutput(); } }
存在问题
package com.zyiz.output; import com.zyiz.output.IOutputGenerator; import com.zyiz.output.impl.CsvOutputGenerator; public class OutputHelper { IOutputGenerator outputGenerator; public OutputHelper(){ outputGenerator = new CsvOutputGenerator(); } public void generateOutput(){ outputGenerator.generateOutput(); } }
package com.zyiz.netmon; import com.zyiz.output.OutputHelper; public class App { public static void main( String[] args ) { OutputHelper output = new OutputHelper(); output.generateOutput(); } }
存在问题
package com.zyiz.output; import com.zyiz.output.IOutputGenerator; public class OutputHelper { IOutputGenerator outputGenerator; public void generateOutput(){ outputGenerator.generateOutput(); } public void setOutputGenerator(IOutputGenerator outputGenerator){ this.outputGenerator = outputGenerator; } }
<!-- Spring-Common.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-2.5.xsd"> <bean id="OutputHelper" class="com.zyiz.output.OutputHelper"> <property name="outputGenerator" ref="CsvOutputGenerator" /> </bean> <bean id="CsvOutputGenerator" class="com.zyiz.output.impl.CsvOutputGenerator" /> <bean id="JsonOutputGenerator" class="com.zyiz.output.impl.JsonOutputGenerator" /> </beans>
通过Spring来调用它
package com.zyiz.netmon; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.zyiz.output.OutputHelper; public class App { public static void main( String[] args ) { ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml"}); OutputHelper output = (OutputHelper)context.getBean("OutputHelper"); output.generateOutput(); } }