+TypeScript 예제
호출부는 IImage로 그리기를 요청하고, 프록시는 실제 객체를 언제 만들지 결정한다. 생성 지연 조건을 화면마다 반복하지 않으려고 접근 제어와 실제 그리기를 나눈다.
// 실제 객체와 대리 객체를 호출부가 같은 방식으로 쓰게 한다.
interface IImage { draw(): string; }
class RealImage implements IImage {
static created = 0;
constructor() { RealImage.created++; }
draw(): string { return "draw image"; }
}
// 생성 시점만 제어하고 실제 작업은 생성한 객체에 위임한다.
class ImageProxy implements IImage {
#image: RealImage | undefined;
draw(): string {
this.#image ??= new RealImage();
return this.#image.draw();
}
}
const image: IImage = new ImageProxy();
console.log(RealImage.created);
console.log(image.draw());
console.log(image.draw());
console.log("created: " + RealImage.created);
0
draw image
draw image
created: 1
TypeScript에서는 #image에 실제 객체를 보관해 C# Lazy<RealImage>의 지연 생성 역할을 표현했다. draw()의 결과를 캐시하는 것이 아니라 객체를 재사용하며, 실제 이미지 파일은 읽지 않는다.