设计模式之动态代理模式
1.创建一个接口
interface Human{
String getBelief();
void eat(String food);
}
2.创建一个被代理类
,并实现接口Human
//被代理类
class SuperMan implements Human{
@Override
public String getBelief() {
return "I believe I can fly!";
}
@Override
public void eat(String food) {
System.out.println("我喜欢吃" + food);
}
}
3.创建一个自定义MyInvocationHandler
并实现InvocationHandler
接口
class MyInvocationHandler implements InvocationHandler{
private Object obj;//需要使用被代理类的对象进行赋值
public void bind(Object obj){
this.obj = obj;
}
//当我们通过代理类的对象,调用方法a时,就会自动的调用如下的方法:invoke()
//将被代理类要执行的方法a的功能就声明在invoke()中
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//method:即为代理类对象调用的方法,此方法也就作为了被代理类对象要调用的方法
//obj:被代理类的对象
Object returnValue = method.invoke(obj,args);
//上述方法的返回值就作为当前类中的invoke()的返回值。
return returnValue;
}
}
4.创建一个代理工厂类
class ProxyFactory{
//调用此方法,返回一个代理类的对象。解决问题一
public static Object getProxyInstance(Object obj){//obj:被代理类的对象
MyInvocationHandler handler = new MyInvocationHandler();
handler.bind(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),handler);
}
}
5.测试类
public class ProxyTest {
public static void main(String[] args) {
SuperMan superMan = new SuperMan();
//proxyInstance:代理类的对象
Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan);
//当通过代理类对象调用方法时,会自动的调用被代理类中同名的方法
String belief = proxyInstance.getBelief();
System.out.println(belief);
proxyInstance.eat("四川麻辣烫");
}
}
或者可以直接不写代理工厂类
,方式如下:
1.创建一个接口
interface Human{
String getBelief();
void eat(String food);
}
2.创建一个被代理类
,并实现接口Human
//被代理类
class SuperMan implements Human{
@Override
public String getBelief() {
return "I believe I can fly!";
}
@Override
public void eat(String food) {
System.out.println("我喜欢吃" + food);
}
}
3.创建一个自定义MyInvocationHandler
并实现InvocationHandler
接口
class MyInvocationHandler implements InvocationHandler{
private Object obj;//需要使用被代理类的对象进行赋值
public MyInvocationHandler(){
}
public MyInvocationHandler(Object obj){
this.obj = obj;
}
//当我们通过代理类的对象,调用方法a时,就会自动的调用如下的方法:invoke()
//将被代理类要执行的方法a的功能就声明在invoke()中
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//method:即为代理类对象调用的方法,此方法也就作为了被代理类对象要调用的方法
//obj:被代理类的对象
Object returnValue = method.invoke(obj,args);
//上述方法的返回值就作为当前类中的invoke()的返回值。
return returnValue;
}
}
4.测试类
public class ProxyTest {
@Test
public void test1(){
SuperMan superMan = new SuperMan();
MyInvocationHandler myInvocationHandler=new MyInvocationHandler(superMan);
Human human = (Human)Proxy.newProxyInstance(superMan.getClass().getClassLoader(), superMan.getClass().getInterfaces(), myInvocationHandler);
String belief = human.getBelief();
System.out.println(belief);
human.eat("苹果");
}
}