1.抽象类
package com.zpark.service; /** * 定义一个环境接口,所有省治理环境的方式都实现这个接口,并重写治理环境的方法 * @author tong * */ public interface Environmental { public void governanceEnvironment(); }
2.实现类
package com.zpark.service.impl; public class BeijingEnvironmental implements Environmental{ @Override public void governanceEnvironment() { System.out.println("【北京市治理环境的方法】"); } }
package com.zpark.service.impl; public class TianjinEnvironmental implements Environmental{ @Override public void governanceEnvironment() { System.out.println("【天津市治理环境的方法】"); } }
package com.zpark.service.impl; public class HebeiEnvironmental implements Environmental{ @Override public void governanceEnvironment() { System.out.println("【河北省治理环境的方法】"); } }
3、简单工厂类
package com.zpark.utils; public class EnvironmentalSimpleFactory { //根据参数创建对象,这是一个静态方法可以直接使用类名调用 public static Environmental createSalary(String name) { Class<Environmental> clazz = null; Environmental salary = null; try { //利用反射机制获取该参数对应的类的对象 clazz = (Class<Environmental>) Class.forName(name); //使用此类对象创建对应的环境类对象,这里使用父类指针指向子类对象,实现了多态 salary = (Environmental)clazz.newInstance(); }catch (Exception e) { e.printStackTrace(); } return salary; } }
4、测试方法
package com.zpark.test; import org.junit.Test; /** * @author ceshi * @Title: ${file_name} * @Package ${package_name} * @Description: ${todo} * @date 2018/6/818:53 */ public class EnvironmentalJunitTest { @Test public void test(){ //创建Client对象,以此对象调用computeSalary()方法传入要类型参数 new EnvironmentalJunitTest().computeSalaryEnvironmental("com.zpark.service.impl.BeijingEnvironmental"); new EnvironmentalJunitTest().computeSalaryEnvironmental("com.zpark.service.impl.HebeiEnvironmental"); new EnvironmentalJunitTest().computeSalaryEnvironmental("com.zpark.service.impl.TianjinEnvironmental"); } /** * 根据传入的参数调用工厂类的创建环境治理方法,创建不同的薪资对象 * @param name */ public void computeSalaryEnvironmental(String name) { //这里使用多态,根据传入参数的不同,生成ZhejiangSalary或者HebeiSalary对象 Environmental environmental = EnvironmentalSimpleFactory.createSalary(name); //使用生成的对象动态调用具体类对象的方法 environmental.governanceEnvironment(); } }
5.测试结果