public class Client { /** * @param args */ public static void main(String[] args) { Person p = new Person(); PersonTimeProxy ptp = new PersonTimeProxy(p); PersonLogProxy plp = new PersonLogProxy(ptp); plp.buy(); } } ---------------------------------------------------------- public interface ProxyInter { public void buy(); } ---------------------------------------------------------- import java.util.Random; public class Person implements ProxyInter{ public void buy() { System.out.println("person buy something………"); try { Thread.sleep(new Random().nextInt(10000)); } catch (InterruptedException e) { e.printStackTrace(); } } } ------------------------------------------------------ public class PersonLogProxy implements ProxyInter { private ProxyInter pi; public PersonLogProxy(ProxyInter pi) { super(); this.pi = pi; } public void buy() { System.out.println("log write"); pi.buy(); System.out.println("log over"); } } -------------------------------------------------------- public class PersonTimeProxy implements ProxyInter { private ProxyInter pi; public PersonTimeProxy(ProxyInter pi) { super(); this.pi = pi; } public void buy() { long start = System.currentTimeMillis(); System.out.println("starttime:"+start); pi.buy(); long end = System.currentTimeMillis(); System.out.println("alltime:"+(end - start)); } 这里的重点是都实现ProxyInter接口。 在每个代理类中都 有一个ProxyInter的引用。 即为:聚合。(推荐使用) 代理还有一种就 是: 继承。(一般不用)