//抽象角色
public interface Star {
void sing();
void sign();
void bookticket();
void money();
void talk();
}
//真是角色
public class RealStar implements Star{
@Override
public void sing() {
System.out.println("唱歌");
}
@Override
public void sign() {
System.out.println("签订合同");
}
@Override
public void bookticket() {
System.out.println("售票");
}
@Override
public void money() {
System.out.println("薪水");
}
@Override
public void talk() {
System.out.println("洽谈");
}
}
//代理角色
public class Proxy implements Star {
private Star Star;
public Proxy(Star Star){
this.Star=Star;
}
@Override
public void sing() {
Star.sing();
}
@Override
public void sign() {
Star.sign();
}
@Override
public void bookticket() {
Star.bookticket();
}
@Override
public void money() {
Star.money();
}
@Override
public void talk() {
Star.talk();
}
}
public class Test {
public static void main(String[] args) {
Star realStar=new RealStar();
Star proxy=new Proxy(realStar);
proxy.talk();
proxy.sign();
proxy.bookticket();
proxy.sing();
proxy.money();
}
}
通过代理Proxy,控制对对象的访问。
public class StarHandler implements InvocationHandler {
private Star star;
public StarHandler(Star star){
this.star=star;
}
//获得代理对象
public Object getProxy(){
return Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{Star.class}, this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
method.invoke(star,args);
return null;
}
}
public class Test02 {
public static void main(String[] args) {
Star star=new RealStar();
StarHandler handler = new StarHandler(star);
Star proxy = (Star) handler.getProxy();
proxy.talk();
proxy.sign();
proxy.bookticket();
proxy.sign();
proxy.money();
}
}