728x90
반응형
💡Proxy Pattern
- 대리인 이라는 뜻으로, 뭔가를 대신해서 처리하는 것
- Proxy Class를 통해 대신 전달하는 형태로 설계되며, 실제 클라이언트는 Proxy로 부터 결과를 받음.
- Cache의 기능으로도 활용이 가능
- SOLID중에서 개방폐쇄원칙(OCP)과 의존 역전 원칙(DIP)를 따른다.
- 개방 폐쇄의 원칙(OCP)이란 기존의 코드를 변경하지 않으면서, 기능을 추가할 수 있도록 설계가 되어야 한다는 원칙을 말한다
- 의존 역전 원칙(DIP)란 객체는 저수준 모듈보다 고수준 모듈에 의존해야한다.
- 고수준 모듈 : 인터페이스와 같은 객체의 형태나 추상적 개념
- 저수준 모듈 : 구현된 객체
- 고/저수준 모델의 정의는 위와 같다. 위 정의를 의존성 역전 원칙에 대입하면, 객체는 객체보다 인터페이스에 의존해야한다로 치환할 수 있다.
- 즉, 가급적 객체의 상속은 인터페이스를 통해 이루어져야 한다는 의미로 해석할 수 있다.[
- [참고] OOP] 객체지향 5원칙(SOLID) - 의존성 역전 원칙 (Dependency Inversion Principle) - 𝝅번째 알파카의 개발 낙서장
👩🏻💻 Proxy 패턴 코드로 알아보기
- IBrower 인터페이스
public interface IBrowser {
Html show();
}
- Browser 클래스
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);
}
}
- Html 클래스
public class Html {
private String url;
public Html(String url){
this.url = url;
}
}
- Browser Test - main 클래스
public class Main {
public static void main(String[] args) {
/*일반 브라우저 인스턴스*/
Browser browser = new Browser("www.naver.com");
browser.show(); //browser loading html from : www.naver.com
browser.show(); //browser loading html from : www.naver.com
browser.show(); //browser loading html from : www.naver.com
browser.show(); //browser loading html from : www.naver.com
browser.show(); //browser loading html from : www.naver.com
browser.show(); //browser loading html from : www.naver.com
}
}
- BrowerProxy 클래스
public class BrowerProxy implements IBrowser{
private String url;
private Html html;
public BrowerProxy(String url){
this.url = url;
}
@Override
public Html show() {
if(html == null){
this.html = new Html(url);
System.out.println("BrowerProxy loading html from : " + url );
}
System.out.println(("BrowserProxy use cache html :" + url));
return html;
}
}
- Proxy Test - main 클래스
public class Main {
public static void main(String[] args) {
/*프록시 브라우저 인스턴스 */
IBrowser browserProxy = new BrowerProxy("www.naver.com");
browserProxy.show(); //BrowerProxy loading html from : www.naver.com
browserProxy.show(); //BrowserProxy use cache html :www.naver.com
browserProxy.show(); //BrowserProxy use cache html :www.naver.com
browserProxy.show(); //BrowserProxy use cache html :www.naver.com
browserProxy.show(); //BrowserProxy use cache html :www.naver.com
browserProxy.show(); //BrowserProxy use cache html :www.naver.com
}
}
💡 결과는 첫번째 show 메소드를 호출하면 loading 하고, 그 뒤 show 메소드는 cache 기능처럼 동작한다.
❕AOP 패턴과 유사한 로직을 코드로 알아보기
- 기존 클래스 위와 동일
- AopBrowser 클래스 추가
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("AopBrower html loading from :" + url);
}
after.run();
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("AopBrower html cache : " + url );
return html;
}
}
- Main
import aop.AopBrowser;
import proxy.BrowerProxy;
import proxy.Browser;
import proxy.IBrowser;
import java.util.concurrent.atomic.AtomicLong;
public class Main {
public static void main(String[] args) {
AtomicLong start = new AtomicLong(); //시작시간
AtomicLong end = new AtomicLong(); //종료시간
/*람다식 표현*/
IBrowser aopBrowser = new AopBrowser("www.naver.com",
() -> { //before
System.out.println("before");
start.set(System.currentTimeMillis()); //현재 시작시간 셋팅
},
() -> { //after
long now = System.currentTimeMillis();
end.set(now - start.get()); //현재시간 - 시작시간 = 걸린시간 셋팅
}
);
aopBrowser.show();
System.out.println("loading time : " + end.get());
/* [result 1]
before
AopBrower html loading from :www.naver.com
AopBrower html cache : www.naver.com
loading time : 1
*/
aopBrowser.show();
System.out.println("loading time : " + end.get());
/* [result 2]
before
AopBrower html cache : www.naver.com
loading time : 0
*/
}
}
💡 url, Runnable 형 매개변수를 받는 AopBrower 생성자를 통해 인스턴스 생성한다.
- 첫번째, show() 호출
- 생성자를 통해 받았던 before Runnable이 실행된다.
- before.run();
- 그러면서, 현재시간을 시작시간으로 셋팅한다.
- html 객체가 처음엔 null 이기 때문에 html 객체를 생성해준다.
- AopBrower html loading from :www.naver.com 를 출력한다.
- 생성자를 통해 받았던 after Runnable이 실행된다.
- after.run();
- Thread.sleep(1500)을 통해 1.5 초 휴식 후,
- AopBrower html cache : www.naver.com 를 출력한다.
- 생성자를 통해 받았던 before Runnable이 실행된다.
- 두번째, show() 호출
- 첫번째 show() 호출과 동일하나, 이미 객체가 생성되어있기 때문에, loading time 이 0임을 볼 수 있다.
- 이미 객체가 생성되었기 때문에 AopBrower html cache : www.naver.com 만 출력한다.
728x90
반응형
'Java' 카테고리의 다른 글
[Java] Adapter pattern (0) | 2023.01.10 |
---|---|
[Java] 싱글톤(Singleton) 패턴 (0) | 2023.01.10 |
[Java] 큐(Queue) 구현 (2) | 2023.01.08 |
[Java] 스택(Stack) 구현 (0) | 2023.01.08 |
[Java] 연결 리스트(LinkedList) (0) | 2023.01.03 |