版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
实现动态调用,方法有很多种,在这里记下一种我觉得比较简单的,方便以后翻阅。
接口类
package com.su.mybatis.oracle.service;
public interface TestService {
String firstStep();
String secondStep();
String thirdStep();
}
接口实现类
1)、TestServiceImplA
package com.su.mybatis.oracle.service.impl;
import com.su.mybatis.oracle.service.TestService;
public class TestServiceImplA implements TestService {
@Override
public String firstStep() {
return "TestServiceImplA--firstStep";
}
@Override
public String secondStep() {
return "TestServiceImplA--secondStep";
}
@Override
public String thirdStep() {
return "TestServiceImplA--thirdStep";
}
}
2)、 TestServiceImplB
package com.su.mybatis.oracle.service.impl;
import com.su.mybatis.oracle.service.TestService;
public class TestServiceImplB implements TestService {
@Override
public String firstStep() {
return "TestServiceImplB--firstStep";
}
@Override
public String secondStep() {
return "TestServiceImplB--secondStep";
}
@Override
public String thirdStep() {
return "TestServiceImplB--thirdStep";
}
}
工厂
emmm,因为我不想以后增加新的实现类时再来修改这个类,里面其实是使用反射实现的,而不是工厂模式。
package com.su.mybatis.oracle.factory;
import com.su.mybatis.oracle.constants.TestEnum;
import com.su.mybatis.oracle.service.TestService;
public class TestFactory {
public static TestService getTestService(String mark){
try {
String path = TestEnum.getPathByMark(mark);
return (TestService)Class.forName(path).newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
枚举类
以后增加新的实现的时候,只需要增加一个枚举值即可。
package com.su.mybatis.oracle.constants;
public enum TestEnum {
A("1","com.su.mybatis.oracle.service.impl.TestServiceImplA"),B("2","com.su.mybatis.oracle.service.impl.TestServiceImplB");
private String mark;
private String path;
private TestEnum(String mark, String path) {
this.mark = mark;
this.path = path;
}
public static String getPathByMark(String mark) {
for (TestEnum testEnum : TestEnum.values())
if (mark.equals(testEnum.getMark()))
return testEnum.getPath();
return null;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
测试方法
package com.su.mybatis.oracle.controller;
import com.su.mybatis.oracle.factory.TestFactory;
import com.su.mybatis.oracle.service.TestService;
public class Test {
public static void main(String[] args) {
TestService t1 = TestFactory.getTestService("1");
System.out.println(t1.firstStep());
System.out.println(t1.secondStep());
System.out.println(t1.thirdStep());
System.out.println("-----------");
TestService t2 = TestFactory.getTestService("2");
System.out.println(t2.firstStep());
System.out.println(t2.secondStep());
System.out.println(t2.thirdStep());
}
}
输出结果:
TestServiceImplA--firstStep
TestServiceImplA--secondStep
TestServiceImplA--thirdStep
-----------
TestServiceImplB--firstStep
TestServiceImplB--secondStep
TestServiceImplB--thirdStep
如果有写的不对的地方,请大家多多批评指正,非常感谢!