반응형
Proxy Pattern
- 대리인 이라는 뜻으로, 뭔가를 대신해서 처리하는 것이다.
- Proxy Class를 통해서 대신 전달하는 형태로 설계되며, 실제 Client는 Proxy로 부터 결과를 받는다.
- Cache의 기능으로도 활용이 가능하다.
- SOLID중에서 개방폐쇄 원칙(OCP)과 의존 역전 원칙(DIP)를 따른다.
Html.java
public class Html {
private String url;
public Html(String url) {
this.url = url;
}
}
IBrowser.java
public interface IBrowser {
Html show();
}
Browser.java
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);
}
}
BrowserProxy.java
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 form : " + url);
}
System.out.println("BrowserProxy use cache html : " + url);
return html;
}
}
AopBrowser.java
import com.example.demo.proxy.Html;
import com.example.demo.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;
}
}
DemoApplication.java
import com.example.demo.aop.AopBrowser;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.concurrent.atomic.AtomicLong;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
Browser browser = new Browser("www.naver.com");
browser.show();
browser.show();
System.out.println("");
IBrowser browser1 = new BrowserProxy("www.daum.net");
browser1.show();
browser1.show();
System.out.println("");
AtomicLong start = new AtomicLong();
AtomicLong end = new AtomicLong();
IBrowser aopBrowser = new AopBrowser("www.google.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());
}
}
스프링 AOP
- 프록시 기반의 AOP 구현체이며, 스프링 Bean에만 AOP 적용 가능하다.
반응형
'JAVA' 카테고리의 다른 글
[Java] 디자인 패턴 - Observer (0) | 2022.08.03 |
---|---|
[JAVA] 디자인 패턴 - Decorator (0) | 2022.08.03 |
[JAVA] 디자인 패턴 - Singleton, Adapter (0) | 2022.08.02 |
[JAVA] 객체지향 설계 5원칙 SOLID (0) | 2022.08.02 |
[JAVA] Spring Boot 프로젝트 생성 & DevTools 적용 (0) | 2022.08.02 |
댓글