책의 예시들을 typescript로 작성하였습니다. 의미가 안 맞을 수 있지만 최대한 비슷한 느낌으로 작성하려 노력했습니다🥺
getter
와 setter
)// 자료 구조
interface Vehicle {
getFuelTankCapacityInGallons(): number; // 연료탱크 용량(갤런 단위)
getGallonsOfGasoline(): number; // 가솔린 (갤런 단위)
}
// 멤버 변수를 그냥 준다.
class Car implements Vehicle {
fuelTankCapacityInGallons: number = 0 // 초기값
gallonsOfGasoline: number = 0 // 초기값
getFuelTankCapacityInGallons() {
return this.fuelTankCapacityInGallons;
}
getGallonsOfGasoline() {
return this.gallonsOfGasoline;
}
}
// 객체
interface Vehicle {
getPercnetFuelRemain(): number;
}
class Car implements Vehicle {
constructor(public fuelTankCapacityInGallons: number, public gallonsOfGasoline: number) {
if (this.fuelTankCapacityInGallons <= 0) {
throw new Error('fuelTankCapacityInGallons must be greater than zero');
}
}
getPercnetFuelRemain(): number {
return (this.gallonsOfGasoline / this.fuelTankCapacityInGallons) * 100;
}
}
절차적인 코드 : 기존 자료 구조를 변경하지 않으면서 새 함수를 추가하기 쉽다.
절차적인 코드는 새로운 자료 구조를 추가하기 어렵다. → 함수를 고쳐야 하기 때문
// 절차적인 코드
class Square {
constructor(public topLeft: number, public side: number) {}
}
class Rectangle {
constructor(public width: number, public height: number) {}
}
class Circle {
constructor(public center: number, public radius: number) {}
}
class Geometry {
PI: number = Math.PI;
area(shape: object): number {
if (shape instanceof Square) {
const s: Square = new Square(shape.topLeft, shape.side);
return s.side * s.side;
} else if (shape instanceof Rectangle) {
const r: Rectangle = new Rectangle(shape.width, shape.height);
return r.height * r.width;
} else if (shape instanceof Circle) {
const c: Circle = new Circle(shape.center, shape.radius);
return this.PI * c.radius * c.radius;
}
throw new Error('No such Shape exception');
}
}
객체 지향 코드 : 기존 함수를 변경하지 않으면서 새 클래스를 추가하기 쉽다. → 하지만 함수를 추가해야 한다
// **객체 지향 코드**
interface Shape {
area():number
}
class Square implements Shape {
constructor(private topLeft: number, private side: number) {}
area():number {
return this.side * this.side;
}
}
class Rectangle implements Shape {
constructor(private topLeft: number,private width: number, private height: number) {}
area():number {
return this.height * this.width;
}
}
class Circle implements Shape {
private PI: number = Math.PI;
constructor(public center: number, public radius: number) {}
area():number {
return this.PI * this.radius * this.radius;
}
}