java中的静态代理:真实对象和代理对象都要实现同一个接口,代理对象要代理真实的角色,也就是说要把真实的角色传入代理对象中并在必要时调用真实对象的方法,但大多数情况都是利用代理对象去做真实对象做不了的事情,解放真实的对象,使真实的对象专注做自己的事情。
public class StacticProxy { public static void main(String[] args) { WeddingCompany weddingCompany = new WeddingCompany(new You());//创建并传入目标函数 weddingCompany.HappyMarry(); } } interface Marry{ void HappyMarry(); } class You implements Marry{ @Override public void HappyMarry(){ System.out.println("happy Day"); } } class WeddingCompany implements Marry{ private Marry target;//目标对象 public WeddingCompany (Marry target){//构造函数 this.target=target; } @Override public void HappyMarry(){ before(); this.target.HappyMarry(); after(); } private void after() {//私有方法 System.out.println("...之后..."); } private void before() {//私有方法 System.out.println("...之前..."); } }