静态代理-可以通过类代理也可以通过接口代理
动态代理只能通过接口代理,但比静态代理灵活
静态代理实例
/**
* 静态代理可通过接口或者类进行代理
* @author Administrator
*
*/
public class StaticProxyTest {
public static void main(String[] args) {
//基于接口
MyPhone myPhone = new MyPhoneImpl();
StaticProxy proxy = new StaticProxy(myPhone);
proxy.name("华为");
//基于类
MyPhoneClass myPhoneClass = new MyPhoneClass();
ProxyEntity entity = new ProxyEntity(myPhoneClass);
entity.name("小米");
}
}
/**
* 接口
* @author Administrator
*
*/
interface MyPhone{
public void name(String str);
}
/**
* 接口实现类
* @author Administrator
*
*/
class MyPhoneImpl implements MyPhone{
@Override
public void name(String str) {
System.out.println("早上好"+str);
}
}
/**
* 自定义静态代理类
* @author Administrator
*
*/
class StaticProxy implements MyPhone{
MyPhone myPhone;
public StaticProxy(MyPhone myPhone) {
this.myPhone = myPhone;
}
@Override
public void name(String str) {
beforeFun();
myPhone.name(str);
afterFun();
}
public void beforeFun(){
System.out.println("前置代理");
}
public void afterFun(){
System.out.println("后置代理");
}
}
/**
* 实体类
* @author Administrator
*
*/
class MyPhoneClass{
public void name(String str){
System.out.println("基于类实现:"+str);
}
}
/**
* 基于类的代理
* @author Administrator
*
*/
class ProxyEntity extends MyPhoneClass{
MyPhoneClass myPhone;
public ProxyEntity(MyPhoneClass myPhone) {
this.myPhone = myPhone;
}
@Override
public void name(String str) {
beforeFun();
myPhone.name(str);
afterFun();
}
public void beforeFun(){
System.out.println("前置代理");
}
public void afterFun(){
System.out.println("后置代理");
}
}
动态代理实例
public class DynamicProxy implements InvocationHandler{
private Object subject;//代理的真实对象
public DynamicProxy(Object subject) {
this.subject = subject;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//添加前置
beforeFun();
//主方法
method.invoke(subject, args);
//添加后置
afterFun();
return null;
}
public void beforeFun(){
System.out.println("前置代理");
}
public void afterFun(){
System.out.println("后置代理");
}
}
public class Test {
public static void main(String[] args) {
//代理的真实对象
Phone myPhone = new MyPhone();
//获取代理类,将真实对象放入代理类中
InvocationHandler dynamicProxy = new DynamicProxy(myPhone);
//调用Proxy的newProxyInstace方法创建代理对象
Phone phone = (Phone) Proxy.newProxyInstance(dynamicProxy.getClass().getClassLoader(), myPhone.getClass().getInterfaces(), dynamicProxy);
phone.name("华为");
phone.price(1000);
}
}