说明:传统的三层架构中 dao层、service层相互依赖,本实例使用工厂模式生成service和dao类,并实现他们之间的相互依赖关系,另糅合动态代理功能,以作学习之用 |
---|
结构图
dao类
public interface UserDao {
void login();
void regist();
}
dao实现类
public class UserDaoImpl implements UserDao{
@Override
public void login() {
System.out.println("登录成功!");
}
@Override
public void regist() {
System.out.println("注册成功!");
}
}
service类
public interface UserService extends BasicService{
void login();
void regist();
}
service实现类
public class UserServiceImpl implements UserService{
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void login() {
/**
* 此处的code并没有实际意义,主要是配合动态代理的方法使用
*/
int code = 0;
for(int i=0; i<100000; i++) {
code +=i;
}
userDao.login();
System.out.println("登录id=" + code);
}
@Override
public void regist() {
/**
* 此处的code并没有实际意义,主要是配合动态代理的方法使用
*/
int code = 0;
for(int i=0; i<100000; i++) {
code +=i;
}
userDao.regist();
System.out.println("注册id=" + code);
}
}
DaiLi 动态代理类
/**
* 柔和一个动态代理的功能实现
* 作用是计算每个方法执行的 时间
* 例如:我想知道login()方法执行完毕需要多少时间,
* 普通做法是在login()之前调用System.currentTimeMillis();
* login()结束后再调用System.currentTimeMillis(),取差;
* 这里我直接使用动态代理替我们实现
* @author Jam
*
*/
public class DaiLi implements InvocationHandler{
private Object object;
public DaiLi(Object object) {
super();
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
long beginTime = System.currentTimeMillis();
method.invoke(object, args);
long endTime = System.currentTimeMillis();
System.out.println(method.getName() + "花费了 "+ (endTime - beginTime) + " 毫秒");
return null;
}
}
BasicService【一个空的接口】
/**
* 空接口
* 让service继承它,作用是判定一个类是不是service类型
*在ObjectFactory类中我们将使用它
* @author Jam
*
*/
public interface BasicService {
}
配置文件 factory.properties
里面存放着我们需要的对象,让对象工厂去生成,注意点:dao必须全部写在service上面,至于为什么这么做,你可以思考一下。
userDao=com.example.dao.impl.UserDaoImpl
userService=com.example.service.impl.UserServiceImpl
核心 ObjectFactory类
@SuppressWarnings("rawtypes")
public class ObjectFactory {
private static Map<String, Object> objectMap = new HashMap<String, Object>();
static {
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(
ObjectFactory.class.getClassLoader().getResourceAsStream("factory.properties")));
try {
String readLine = br.readLine();
while(null != readLine) {
String[] str = readLine.split("=");
String key = str[0];
Class clazz;
try {
clazz = Class.forName(str[1]);
Object object = clazz.newInstance();
objectMap.put(key, object);
if(object instanceof BasicService) {
//给service类设置dao属性
autowire(object);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
readLine = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}finally {
if(null != br) {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 在properties中查询组装的类如果是service类
* 在生成service对象之后还得service.setDao
* @param target
*/
public static void autowire(Object target) {
Class<? extends Object> clazz = target.getClass();
Field[] fileds = clazz.getDeclaredFields();
for(Field field:fileds) {
String fieldName = field.getName(); //userdao
Class fieldType = field.getType(); //Userdao
String methodName = "set" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
Method method;
try {
method = clazz.getDeclaredMethod(methodName, fieldType);
method.invoke(target, objectMap.get(fieldName));
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
/**
* 对象工厂的主方法,根据key返回一个对象
* @param key
* @return
*/
public static Object createObject(String key) {
return objectMap.get(key);
}
}
测试类
/**
* 测试类
* @author Jam
*
*/
public class TestFactory {
public static void main(String[] args) {
//用对象工厂生成 UserServiceImpl
UserService userService = (UserService)ObjectFactory.createObject("userService");
//每一个被代理对象或者被代理类都有一个InvocationHandler对象
InvocationHandler handler= new DaiLi(userService);
//生成代理对象
UserService handlerUserService = (UserService)Proxy.newProxyInstance(
UserServiceImpl.class.getClassLoader(), UserServiceImpl.class.getInterfaces(), handler);
//代理对象执行任务
handlerUserService.login();
System.out.println();
handlerUserService.regist();
}
}
执行结果
登录成功!
登录id=704982704
login花费了3毫秒
注册成功!
注册id=704982704
regist花费了1毫秒