1、新建抽象类AbstractUser
package com.kobe.model;public abstract class AbstractUser { public abstract void work();}
2、新建继承AbstractUser 的 AbstractStudent 、 AbstractTeacher
package com.kobe.model;public class AbstractTeacher extends AbstractUser{ private int id; private String name; @Override public void work(){ System.out.println("teach"); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
package com.kobe.model;public class AbstractStudent extends AbstractUser { private int id; private String name; @Override public void work(){ System.out.println("study"); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
3、在resources目录下新建配置文件 obj.properties
AbstractModel = com.kobe.model.AbstractStudent
4、新建工厂类 getUser方法 从配置文件中读取配置信息
package com.kobe.test;import com.kobe.model.AbstractUser;import java.util.Properties;public class AbstractFactory { public static AbstractUser getUser(){ try { Properties prop = new Properties(); prop.load(simpleFactory.class.getClassLoader().getResourceAsStream("obj.properties")); String model = (String) prop.get("AbstractModel"); AbstractUser u = (AbstractUser) Class.forName(model).newInstance(); return u; } catch (Exception e) { e.printStackTrace(); } return null; }}
5、新建测试类
package com.kobe.test;import com.kobe.model.AbstractUser;public class testAbstract { public static void main(String[] args) { AbstractUser u1 = AbstractFactory.getUser(); u1.work(); }}
输出结果是 study
如果把配置文件中的 AbstractModel的值换成 com.kobe.model.AbstractTeacher
输出就变成 teach
根据配置文件创建不同的实体类,不需修改java代码