静态代理和动态代理的区别

静态代理

举个例子:
有个接口A
创建AImpl类实现接口
创建AProxy类来隐藏和保护A和AImpl,并且可以在其中添加新的功能
优点是:保护和隐藏了要代理的类
缺点是:感觉代码繁多,类很多,并且随着接口和实现接口的类变多,那么需要代理的类也就越多。

案例:

public interface UserService {
	void login();
	void regist();
}
public class UserServiceImpl implements UserService{
	@Override
	public void login() {
		System.out.println("登录方法");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	@Override
	public void regist() {
		System.out.println("注册功能");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

public class UserServiceproxy implements UserService{
	private UserService userService;
	public UserServiceproxy(UserService userService) {
		super();
		this.userService = userService;
	}
	@Override
	public void login() {
		long startTime = System.currentTimeMillis();
		userService.login();
		long endTime = System.currentTimeMillis();
		System.out.println("UserService.login()方法耗时间:" +(endTime - startTime) + "毫秒");
	}
	@Override
	public void regist() {
		long startTime = System.currentTimeMillis();
		userService.regist();
		long endTime = System.currentTimeMillis();
		System.out.println("UserService.regist()方法耗时间:" +(endTime - startTime) + "毫秒");
	}

}

public class TestUserService {
	public static void main(String[] args) {
		UserService userServiceImpl = new UserServiceImpl();
		
		UserService userServiceProxy = new UserServiceproxy(userServiceImpl);
		
		userServiceProxy.login();
		
		userServiceProxy.regist();
	}
}

动态代理

动态代理用了一些反射的原理,是为了更好解决代理的类

public class UserServiceDproxy implements InvocationHandler {
	private Object target;
	public UserServiceDproxy(Object target) {
		super();
		this.target = target;
	}
	public Object newProxyInstance() {
		return Proxy.newProxyInstance(target.getClass().getClassLoader(),
				target.getClass().getInterfaces(), this);
	}
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		long startTime = System.currentTimeMillis();
		Object returnObj = method.invoke(target, args);
		long endTime = System.currentTimeMillis();
		System.out.println(target.getClass().getSimpleName() + "." + method.getName() + "()方法耗时间:" +(endTime - startTime) + "毫秒");
		return returnObj;
	}
}

public class TestUserServiceDproxy {
	public static void main(String[] args) {
		UserService userServiceImpl = new UserServiceImpl();
		
		UserServiceDproxy dproxy = new UserServiceDproxy(userServiceImpl);
		
		UserService j = (UserService) dproxy.newProxyInstance();
		
		j.login();
		
		j.regist();
	}
}

你可能感兴趣的:(静态代理和动态代理的区别)