1 public interface TiketsSystem {
2 void buyTicket();
3 }
1 public class TrainStation implements TiketsSystem{
2 public void buyTicket(){
3 System.out.println("buy a ticket");
4 }
1 public class TicketsProxy implements TiketsSystem{
2 TiketsSystem proxy;
3 TicketsProxy(){}
4 @Override
5 public void buyTicket() {
6 if (proxy == null) {
7 proxy = new TrainStation();
8 }
9 proxy.buyTicket();
10 }
11 }
public class ProxyTest {
public static void main(String[] args) {
TicketsProxy proxy = new TicketsProxy();
proxy.buyTicket();
}
}
1 import java.lang.reflect.InvocationHandler;
2 import java.lang.reflect.Method;
3 import java.lang.reflect.Proxy;
4
5 public class TicketsProxy implements InvocationHandler{
6 private Object proxy;
7
8 // 返回TrainStation的实例来作为代理
9 public Object getProxy (Object p) {
10 proxy = p;
11 return Proxy.newProxyInstance(proxy.getClass().getClassLoader(), proxy.getClass().getInterfaces(), this);
12 }
13
14 // InvocationHandler接口定义的方法
15 @Override
16 public Object invoke(Object proxy, Method method, Object[] args)
17 throws Throwable {
18 // 通过反射调用TrainStation的buyTicket方法
19 Object obj = method.invoke(this.proxy, args);
20 return obj;
21 }
22
23 }
1 public class ProxyTest {
2 public static void main(String[] args) {
3 // 通过getProxy方法获得火车站买票的代理权
4 TiketsSystem proxy = (TiketsSystem)new TicketsProxy().getProxy(new TrainStation());
5 // 代理来买票
6 proxy.buyTicket();
7 }
8 }