728x90
반응형
프로토타입 패턴
: 기존 인스턴스를 복제하여 새로운 인스턴스를 만드는 방법. 기존의 객체를 응용하여 새로운 객체를 만들 때 사용한다. 특히 기존의 인스턴스를 만들 때 시간이 오래걸리는 작업. 가령 데이터 베이스에서 데이터를 읽어와서 인스턴스를 생성한다던가 http 요청을 보내서 가져온 데이터로 인스턴스를 만들어야 하는 경우는 상대적으로 오랜시간과 큰 리소스가 필요한 작업이다. 이 때 DB나 http통신으로 가져온 데이터를 복제를 해서 새로운 인스턴스를 만들고 원하는 값만 일부 변경하여 사용한다.
interface ShapeProperties {
color: string;
x: number;
y: number;
}
abstract class Shape {
constructor(public properties: ShapeProperties) {}
abstract clone(): Shape;
}
class Reactangle extends Shape {
constructor(
properties: ShapeProperties,
public width: number,
public height: number
) {
super(properties);
}
public clone(): Shape { //프로토타입 패턴에서는 clone메서드가 핵심
let clonedProperties: ShapeProperties = {
color: this.properties.color,
x: this.properties.x,
y: this.properties.y,
};
return new Reactangle(clonedProperties, this.width, this.height);
}
}
class Circle extends Shape {
constructor(properties: ShapeProperties, public radius: number) {
super(properties);
}
public clone(): Shape {
let clonedProperties: ShapeProperties = {
color: this.properties.color,
x: this.properties.x,
y: this.properties.y,
};
return new Circle(clonedProperties, this.radius);
}
}
let redRectangle: Shape = new Reactangle(
{
color: "red",
x: 20,
y: 100,
},
10,
20
);
let anotherRectangle: Shape = redRectangle.clone();
anotherRectangle.properties.color = "blue";
console.log(redRectangle);
console.log(anotherRectangle);
728x90
반응형
'개발공부 일지 > 면접' 카테고리의 다른 글
프록시 패턴(Proxy Pattern) (0) | 2023.10.03 |
---|---|
빌더 패턴(Builder Pattern) (0) | 2023.10.02 |
CORS는 무엇이고, CORS 에러를 방지하려면 어떻게 해야하나요? (0) | 2023.10.02 |
싱글톤 패턴(Singleton Pattern) (0) | 2023.10.01 |
SOLID 원칙 (1) | 2023.10.01 |
댓글