728x90
반응형
Proxy Pattern
대리인 이라는 뜻으로, 대신해서 처리하는 것을 말합니다. Proxy Class를 통해서 대신 전달하는 형태로 설계되며, 실제 Client는 Proxy로 부터 결과를 받습니다. 또한 Cache의 기능으로도 활용이 가능합니다. OCP와 DIP를 따릅니다.
Proxy Pattern 으로 캐싱 구현
[Browser interface]
package Java.proxy;
public interface Browser {
HTML show();
}
[Chrome class]
package Java.proxy;
public class Chrome implements Browser{
private String url;
public Chrome(String url) {
this.url = url;
}
@Override
public HTML show() {
System.out.println("browser loading html from: "+url);
return new HTML(url);
}
}
브라우저 인터페이스를 상속받은 크롬 브라우저
이 클래스는 show를 Main에서 계속 호출하면 브라우저를 계속해서 로딩해옵니다. (효율적이지 않습니다.)
효율적으로 작동하게 하기 위해서 프록시 패턴을 사용해 캐싱을 하여 캐싱된 url을 가져오도록 할 수 있습니다.
[ChromeProxy class]
package Java.proxy;
public class ChromeProxy implements Browser{
private String url;
private HTML html;
public ChromeProxy(String url) {
this.url = url;
}
@Override
public HTML show() {
if(html == null){
this.html = new HTML(url);
System.out.println("BrowserProxy loading html from: " + url);
}
System.out.println("BrowserProxy use cache html: " + url);
return html;
}
}
HTML을 필드 변수로 가지고 있기 때문에 이를 저장해놓고
로딩한 적이 있는 html이라면 캐싱된 데이터를 가져오도록 구현하였습니다.
[HTML class]
package Java.proxy;
public class HTML {
private String url;
public HTML(String url) {
this.url = url;
}
}
[ProxyMain class]
package Java.proxy;
public class ProxyMain {
public static void main(String[] args) {
Chrome naver = new Chrome("https://lakelight.tistory.com");
naver.show();
Browser browser = new ChromeProxy("https://lakelight.tistory.com");
browser.show();
browser.show();
browser.show();
}
}
결과
browser loading html from: https://lakelight.tistory.com #첫번째는 로딩을 했고 필드변수 HTML이 저장되었을 것입니다.
BrowserProxy loading html from: https://lakelight.tistory.com # 이후에는 캐싱된 데이터를 바로 출력하는 것을 확인하였습니다.
BrowserProxy use cache html: https://lakelight.tistory.com
BrowserProxy use cache html: https://lakelight.tistory.com
BrowserProxy use cache html: https://lakelight.tistory.com
결론
프록시 패턴을 이용하여 캐싱하는 기능을 구현해보았습니다.
728x90
반응형
'JAVA' 카테고리의 다른 글
[Java] Decorator Pattern - Example Car (0) | 2022.08.01 |
---|---|
[Java] Proxy Pattern - AOP (0) | 2022.07.31 |
[Java] Adapter Pattern (0) | 2022.07.31 |
[Java] Thread Method : wait(), notify() (0) | 2022.07.31 |
[Java] Thread Synchronization (0) | 2022.07.29 |