프록시 모드(정적 및 동적)

3424 단어 프록시 모드
프록시 인터페이스:

package ProxyPattern;

public interface Italk {
	public void talk(String msg);
}

RealSubject:

package ProxyPattern;

public class People implements Italk {
	public String username;
	public String age;

	public String getName() {
		return username;
	}

	public void setName(String name) {
		this.username = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	public People(String name1, String age1) {
		this.username = name1;
		this.age = age1;
	}

	public void talk(String msg) {
		System.out.println(msg + "!  ,  " + username + ",    " + age);
	}
}

프록시 클래스:

package ProxyPattern;

public class TalkProxy implements Italk {
	Italk people;

	public TalkProxy(Italk people) {
		this.people = people;
	}

	public void talkProxy(Italk people) {
		this.people = people;
	}

	public void talk(String msg) {
		people.talk(msg);
	}

	public void talk(String msg, String singname) {
		people.talk(msg);
		sing(singname);
	}

	private void sing(String singname) {
		System.out.println("  :" + singname);
	}
}

테스트:

package ProxyPattern;

public class MyProxyTest {

	public static void main(String[] args) {
		
		People people1 = new People("    ", "18");
		people1.talk("No ProXY Test");
		
		System.out.println("-----------------------------");
		
		TalkProxy talker = new TalkProxy(people1);
		talker.talk("ProXY Test", "   ");
	}
}

다른 프록시 모드: 동적 프록시:

package Dybamic;

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


public class Handler implements InvocationHandler {

	public Object targetObj;

	public Handler(Object targetObj) {
		this.targetObj = targetObj;
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {

		System.out.println("before the function \"" + method.getName() + "\"");
		Object ret = method.invoke(targetObj, args);
		System.out.println(ret);
		System.out.println("after the function \"" + method.getName() + "\"");
		return ret;

	}

	

}

동적 프록시 테스트:

package ProxyPattern;

package Dybamic;

import java.lang.reflect.Proxy;

public class testMain {

	public static void main(String[] args) {

		IUser realUser = new UserImp("sun");
		Handler hand = new Handler(realUser);
		IUser proxy = (IUser) Proxy.newProxyInstance(realUser.getClass()
				.getClassLoader(), realUser.getClass().getInterfaces(), hand);
		proxy.getName();
	}

}

좋은 웹페이지 즐겨찾기