動態代理實例——增強Waiter接口

圖示

在這裏插入圖片描述

代碼

Waiter接口

/*
 * 服務員接口
 */
public interface Waiter {
	// 服務方法
	public void serve();

}

ManWaiter類

public class ManWaiter implements Waiter {

	public void serve() {
		System.out.println("服務中...");
	}

}

Demo

package com.veeja.demo2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.junit.Test;

public class Demo2 {

	@Test
	public void fun1() {
		Waiter manWaiter = new ManWaiter();
		// 創建三大參數
		ClassLoader loader = this.getClass().getClassLoader();
		Class[] interfaces = { Waiter.class };
		// 參數manWaiter表示目標對象
		InvocationHandler h = new WaiterInvocationHandler(manWaiter);

		// 得到代理對象,代理對象就是在目標對象的基礎上進行了增強的對象
		Waiter waiterProxy = (Waiter) Proxy.newProxyInstance(loader,
				interfaces, h);
		// 前面增加你好,後面添加再見。
		waiterProxy.serve();
	}
}

class WaiterInvocationHandler implements InvocationHandler {

	private Waiter waiter;// 創建目標對象

	public WaiterInvocationHandler(Waiter waiter) {
		this.waiter = waiter;

	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {

		System.out.println("您好!");
		this.waiter.serve();// 調用目標對象的目標方法
		System.out.println("再見!");
		return null;
	}

}

END.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章