1. 程式人生 > 其它 >從坐席到外呼,明道雲與品聘雲呼叫對接示例

從坐席到外呼,明道雲與品聘雲呼叫對接示例

  1. 代理分為靜態代理和動態代理兩種。
  2. 靜態代理,代理類需要自己編寫程式碼寫成。
  3. 動態代理,代理類通過 Proxy.newInstance() 方法生成。
  4. 不管是靜態代理還是動態代理,代理與被代理者都要實現兩樣介面,它們的實質是面向介面程式設計。
  5. 靜態代理和動態代理的區別是在於要不要開發者自己定義 Proxy 類。
  6. 動態代理通過 Proxy 動態生成 proxy class,但是它也指定了一個 InvocationHandler 的實現類。
  7. 代理模式本質上的目的是為了增強現有程式碼的功能。
    public interface Image {
        void  display();
    }
    ***************************************************
    public
    class RealImage implements Image { private String fileName; public RealImage(String fileName){ this.fileName = fileName; loadFromDisk(fileName); } @Override public void display() { System.out.println("Displaying " + fileName); } private void loadFromDisk(String fileName){ System.out.println(
    "Loading " + fileName); } } ************************************************** import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class MyInvocationHandler implements InvocationHandler { RealImage realImage; public MyInvocationHandler(RealImage realImage) {
    this.realImage=realImage; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("呼叫代理類"); if(method.getName().equals("display")){ method.invoke(realImage, args); System.out.println("呼叫的是賣書的方法"); return null ; }else { String string = (String) method.invoke(realImage,args) ; System.out.println("呼叫的是說話的方法"); return string ; } } } **************************************************** import java.lang.reflect.Proxy; public class Main { public static void main(String[] args) { RealImage realImage=new RealImage("dada"); MyInvocationHandler myInvocationHandler=new MyInvocationHandler(realImage); Image proxyclass=(Image) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{Image.class}, myInvocationHandler); proxyclass.display(); System.out.println(proxyclass.getClass().getName()); } }