반응형
Proxy는 대리인이라는 뜻으로, 뭔가를 대신해서 처리하는 것
Proxy Class를 통해서 대신 전달하는 형태로 설계되며, 실제 Client는 Proxy로 부터 결과를 받는다.
Cache의 기능으로도 활용이 가능하다.
SOLID중에서 개방폐쇄 원칙(OCP)과 의존 역전 원칙(DIP)를 따른다.
package com.company.design.proxy;
public interface IBrowser {
HTML show();
}
package com.company.design.proxy;
public class HTML {
private String url;
public HTML(String url){
this.url = url;
}
}
package com.company.design.proxy;
public class Browser implements IBrowser{
private String url;
public Browser(String url){
this.url = url;
}
@Override
public HTML show() {
System.out.println("browser loading html from : " + url);
return new HTML(url);
}
}
package com.company.design.proxy;
public class BrowserProxy implements IBrowser{
private String url;
private HTML html;
public BrowserProxy(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;
}
}
package com.company.design.aop;
import com.company.design.proxy.HTML;
import com.company.design.proxy.IBrowser;
public class AopBrowser implements IBrowser {
private String url;
private HTML html;
private Runnable before;
private Runnable after;
public AopBrowser(String url, Runnable before, Runnable after){
this.url = url;
this.before = before;
this.after = after;
}
@Override
public HTML show() {
before.run();
if (html == null){
this.html = new HTML(url);
System.out.println("AopBrowser html loading from : " + url);
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
after.run();
System.out.println("AopBrowser html cache : " + url);
return null;
}
}
package com.company.design;
import com.company.design.adapter.*;
import com.company.design.aop.AopBrowser;
import com.company.design.proxy.Browser;
import com.company.design.proxy.BrowserProxy;
import com.company.design.proxy.IBrowser;
import com.company.design.singleton.Aclazz;
import com.company.design.singleton.Bclazz;
import com.company.design.singleton.SocketClient;
import java.util.concurrent.atomic.AtomicLong;
public class Main {
public static void main(String[] args) {
IBrowser browser = new BrowserProxy("www.naver.com");
browser.show();
browser.show();
browser.show();
browser.show();
AtomicLong start = new AtomicLong();
AtomicLong end = new AtomicLong();
IBrowser aopBrowser = new AopBrowser("www.naver.com",
() -> {
System.out.println("before");
start.set(System.currentTimeMillis());
},
() -> {
long now = System.currentTimeMillis();
end.set(now - start.get());
}
);
aopBrowser.show();
System.out.println("loading time : " + end.get());
aopBrowser.show();
System.out.println("loading time : " + end.get());
}
}
반응형
'언어 > JAVA' 카테고리의 다른 글
Observer pattern (0) | 2021.06.06 |
---|---|
데코레이터 패턴 (0) | 2021.06.06 |
Adapter pattern (0) | 2021.06.06 |
POJO JAVA (0) | 2021.06.06 |
객체지향 설계 5원칙 SOLID (0) | 2021.06.06 |