// 절차적인 코드는 기존 자료 구조를 변경하지 않으면서 새 함수를 추가하기 쉽습니다.
// 기존 자료 구조
class Point {
constructor(public x: number, public y: number) {}
}
// 기존 함수
function printPoint(point: Point) {
console.log(`(${point.x}, ${point.y})`);
}
// 새로운 함수 추가
function distanceFromOrigin(point: Point): number {
return Math.sqrt(point.x * point.x + point.y * point.y);
}
// 객체지향 코드는 기존 함수를 변경하지 않으면서 짜기 쉽습니다
// 기존 클래스
class Point {
constructor(private x: number, private y: number) {}
print() {
console.log(`(${this.x}, ${this.y})`);
}
distanceFromOrigin(): number {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
}
// 새로운 클래스 추가
class PolarPoint {
constructor(private r: number, private theta: number) {}
print() {
console.log(`(${this.r} @ ${this.theta} radians)`);
}
distanceFromOrigin(): number {
return this.r;
}
}
// 절차 적인 코드는 새로운 자료구조를 추가하기가 어렵습니다.
// 새로운 자료 구조
class PolarPoint {
constructor(public r: number, public theta: number) {}
}
// 기존 함수 수정
function printPoint(point: Point | PolarPoint) {
if (point instanceof Point) {
console.log(`(${point.x}, ${point.y})`);
} else {
console.log(`(${point.r} @ ${point.theta} radians)`);
}
}
// 기존 함수 수정
function distanceFromOrigin(point: Point | PolarPoint): number {
if (point instanceof Point) {
return Math.sqrt(point.x * point.x + point.y * point.y);
} else {
return point.r;
}
}
// 객체지향 코드는 새로운 함수를 추가하기 어렵습니다. 그러려면 모든 클래스를 고쳐야합니다.
// 새로운 메서드 추가를 위해 기존 클래스 수정
class Point {
constructor(private x: number, private y: number) {}
print() {
console.log(`(${this.x}, ${this.y})`);
}
distanceFromOrigin(): number {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
// 새로운 메서드 추가
getCoordinates(): { x: number; y: number } {
return { x: this.x, y: this.y };
}
}
// 새로운 메서드 추가를 위해 기존 클래스 수정
class PolarPoint {
constructor(private r: number, private theta: number) {}
print() {
console.log(`(${this.r} @ ${this.theta} radians)`);
}
distanceFromOrigin(): number {
return this.r;
}
// 새로운 메서드 추가
getCoordinates(): { r: number; theta: number } {
return { r: this.r, theta: this.theta };
}
}