Proxy模式

快放假了···难得空闲···整理一下工作中常用的模式放上来···

定义所需要的接口:
  1. package com.xxx;   
  2.   
  3. public interface Artist {   
  4.     public void show();   
  5. }  
实现该接口的类:
  1. package com.xxx;   
  2.   
  3. public class Star implements Artist{   
  4.     private String name = null;   
  5.     private String action = null;   
  6.        
  7.     public String getAction() {   
  8.         return action;   
  9.     }   
  10.   
  11.     public void setAction(String action) {   
  12.         this.action = action;   
  13.     }   
  14.   
  15.   
  16.     public String getName() {   
  17.         return name;   
  18.     }   
  19.   
  20.     public void setName(String name) {   
  21.         this.name = name;   
  22.     }   
  23.   
  24.     public void show() {   
  25.         System.out.println(name + "   " + action);   
  26.     }   
  27. }  
代理类:
  1. package com.xxx;   
  2.   
  3. import java.lang.reflect.InvocationHandler;   
  4. import java.lang.reflect.Method;   
  5. import java.lang.reflect.Proxy;   
  6.   
  7. public class AProxy implements InvocationHandler{   
  8.     private Object delegate = null;   
  9.        
  10.     public Object bind(Object delegate){   
  11.         this.delegate = delegate;   
  12.         return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this);   
  13.     }   
  14.   
  15.     public Object invoke(Object obj, Method method, Object[] args) throws Throwable {   
  16.         System.out.println("签约");   
  17.         Object result = method.invoke(delegate, args);   
  18.         System.out.println("唱完了新闻发布会");   
  19.         return result;   
  20.     }   
  21. }   
测试类:
  1. package com.xxx;   
  2.   
  3. public class TestMain {   
  4.     public static void main(String [] args) {   
  5.         AProxy a = new AProxy();   
  6.         Star star = new Star();   
  7.         ((Star)star).setName("刘德华");   
  8.         ((Star)star).setAction("唱歌");   
  9.         Artist artist = (Artist) a.bind(star);         
  10.         artist.show();         
  11.     }   
  12. }   

运行结果:

签约
刘德华   唱歌
唱完了新闻发布会

你可能感兴趣的:(工作)