代理模式:
一个类代表另一个类的功能
有些事情本应该是你做的,但是你不想做或者不方便做的时候,叫别人替你完成.
静态代理
动态代理
/**
* Created by malei on 2016/12/6.
* 代理人, 由于需要帮委托人带饭, 也必须实现午饭接口
*/
public class ProxyMan implements Lunch {
private final You mYou;
public ProxyMan(You you) {
mYou = you;
}
@Override
public void eat() {
mYou.eat();
}
//静态代理
public static void main(String[] ages){
You you = new You();
ProxyMan man = new ProxyMan(you);
man.eat();
}
//动态代理
public static void main2(String[] ages){
You you = new You();
Lunch people = (Lunch) Proxy.newProxyInstance(
you.getClass().getClassLoader(),
new Class[]{Lunch.class},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
return method.invoke(you,args);
}
});
people.eat();
}
}
/**
* Created by malei on 2016/12/6.
*/
public class You implements Lunch {
@Override
public void eat() {
Log.show("我要吃小炒肝尖!");
}
}
/**
* Created by malei on 2016/12/6.
* 午饭的规范
*/
public interface Lunch {
void eat();
}
网友评论