자바 동적 에이전트 의 실현

동적 에이전트 의 실현 은 정적 에이전트 의 모델 업그레이드 라 고 할 수 있 습 니 다. 만약 에 학생 들 이 대리 모델 의 개념 을 모 르 면 제 앞의 글 을 참고 할 수 있 습 니 다.http://blog.csdn.net/u012481172/article/details/50157079; 다음은 동적 에이전트 가 어떻게 사용 되 는 지 4 단계 로 나 누 어 설명 하 겠 습 니 다.
1. 행위 규범 을 정의 합 니 다.
public interface IService {
    public String doSomething();
}
    이상 의 인 터 페 이 스 는 목표 대상 에 의 해 이 루어 지면 됩 니 다. 왜냐하면 우 리 는 지금 스스로 대 리 를 만 들 필요 가 없 기 때문에 JDK 동적 으로 대 리 를 만 듭 니 다.
2. 자신의 Invocation Handler 실현
   
public class MyInvocationHandler implements InvocationHandler {
	//     
	private Object target;

	public MyInvocationHandler(Object target) {
		super();
		this.target = target;
	}

	/**
	 *        InvocationHandler   
	 *          
	 */
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println("                ...");
		//          
		Object result = method.invoke(target, args);
		System.out.println("                ...");
		return result;
	}

	/**
	 *            
	 * 
	 * @return     
	 */
	public Object getProxy() {
		return Proxy.newProxyInstance(Thread.currentThread()
				.getContextClassLoader(), target.getClass().getInterfaces(),
				this);
	}
}
    이상 은 자신의 Invocation Handler 를 실현 한 것 입 니 다. 이것 은 기본적으로 규범 화 된 쓰기 입 니 다. 그 다음 에 우리 가 자신의 Invocation Handler 를 만들어 야 한다 면 모두 이 형식 에 따라 합 니 다.getProxy () 방법 에서 Proxy 류 를 사 용 했 습 니 다. 이 종 류 는 JDK 다음 시스템 클래스 입 니 다. 제 가 이전 글 에서 자신의 Proxy 류 가 아 닙 니 다.
3. 목표 달성 대상
public class RealService implements IService {
	public String doSomething() {
		System.out.println("           ...");
		return "           ...";
	}
}

4. 대상 의 사용 및 인쇄 테스트
	public static void main(String[] args) {
		//        
		IService userService = new RealService();
		//    InvocationHandler
		MyInvocationHandler invocationHandler = new MyInvocationHandler(
				userService);
		//             
		IService proxy = (IService) invocationHandler.getProxy();
		//          
		proxy.doSomething();
	}

//==================        
                ...
           ...
                ...

 

관련 자료
 (1) 동적 에이전트 의 장점 과 응용 장면: 이동 하 십시오.http://www.zhihu.com/question/20794107;
 (2) 자바 동적 에이전트 에 대한 상세 한 구현: 다음으로 이동 하 십시오.http://rejoy.iteye.com/blog/1627405;  

좋은 웹페이지 즐겨찾기