특정 객체로의 접근을 제어하는 대리인(특정 객체를 대변하는 객체)를 제공하는 패턴이다.
접근 제어 방법
- 원격 프록시를 사용하여 원격 개체로의 접근을 제어할 수 있다.
- 가상 프록시를 써서 생성하기 힘든 자원으로의 접근을 제어할 수 있다.
- 보호 프록시를 써서 접근 권한이 필요한 자원으로의 접근을 제어할 수 있다.
모니터링할 클래스
public class GumballMachine {
String location;
public GumballMachine(String location) {
this.location = location;
}
public String getLocation() { return location; }
모니터링 클래스
public class GumballMonitor{
GumballMachine machine;
// 생성자로부터 객체를 전달받아서 인스턴스 변수에 저장한다.
public GumballMonitor(GumballMachine machine) {
this.machine = machine;
}
public void report() {
System.out.println(machine.getLocation());
}
}
원격 인터페이스
import java.rmi.*;
public interface GumballMachineRemote extends Remote{
public String getLocation() throws RemoteException;
}
서비스 구현 클래스
public class GumballMachine extends UnicastRemoteObject implements MyRemote {
private static final long serverVersionUID = 1L; // serializable
String location;
public GumballMachine(String location) throws RemoteException{ this.location = location; }
public String getLocation(){ return location};
}
서버 테스트
public class GUmballMachineTestDrive{
public static void main(String[] args) {
GumballMachineRemote gumballMachine = null;
try {
gumballMachine = new GumballMachines(args[0]);
// Naming.rebind함수로 GumballMachine 스텁을 GumballMahine이라는 이름으로 등록한다.
Naming.rebind("//" + args[0] + "/gumballmachine", gumballMachine);
} catch(Exception e) {
e.printStackTrace();
}
}
}
클라이언트 클래스
public class GumballMonitor{
GumballMachineRemote machine; // 원격 인터페이스 사용
public GumballMonitor(GumballMachineRemote machine) {
this.machine = machine;
}
public void report() {
try {
System.out.println(machine.getLocation());
} catch(Exception e) {
ex.printStackTrace();
}
}
}
}
Test Class
public static void main(String[] args) {
String[] location = {"rmi:// ..", "rmi://"}; // 모니터링할 위치
GumballMonitor[] monitor = GumballMonitor[location.length];
for(int i = 0; i<location.length; i++){
try{
// 서비스를 RMI 레지스트리에 등록
GumballMachineRemote machine = (GumballMachineRemote) Naming.lookup(location[i]); // 각 기계의 프록시
// 생성자에 모니터링할 객체의 프록시를 넘겨준다.
monitor[i] = new GumballMonitor(machine);
} catch (Exception e){
e.printStackTrace();
}
}
}
서버와 클라이언트 사이에서 클라이언트가 자신을 통해 다른 네트워크 서비스에 간접적으로 접근할 수 있도록 해주는 컴퓨터 시스템이나 응용 프로그램이다.
** CDN: 각 사용자가 인터넷에 접속하는 곳과 가까운 곳에서 콘텐츠를 캐싱 또는 배포하는 서버 네트워크
정보 감사합니다.