본문 바로가기
Javascript

OOP(5)

by Doromi 2023. 11. 7.
728x90
반응형
더 복잡한 객체 지향 프로그래밍(OOP) 예제로 간단한 주문 처리 시스템을 모델링하는 것을 살펴보겠습니다. 이 예제에서는 주문, 제품, 그리고 고객을 다루는 클래스를 만들어 보겠습니다.
// 제품 클래스 정의
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }
}

// 주문 클래스 정의
class Order {
  constructor(customer) {
    this.customer = customer;
    this.items = [];
  }

  addItem(product, quantity) {
    this.items.push({ product, quantity });
  }

  calculateTotal() {
    return this.items.reduce((total, item) => total + item.product.price * item.quantity, 0);
  }

  checkout() {
    const total = this.calculateTotal();
    console.log(`주문 확인: ${this.customer.name}, 총 금액 $${total}`);
  }
}

// 고객 클래스 정의
class Customer {
  constructor(name) {
    this.name = name;
  }
}

// 제품 생성
const product1 = new Product("휴대폰", 500);
const product2 = new Product("노트북", 1000);

// 고객 생성
const customer1 = new Customer("John");
const customer2 = new Customer("Jane");

// 주문 생성
const order1 = new Order(customer1);
const order2 = new Order(customer2);

// 주문에 제품 추가
order1.addItem(product1, 2);
order1.addItem(product2, 1);
order2.addItem(product1, 1);

// 주문 확인
order1.checkout();
order2.checkout();
 Product, Order, 그리고 Customer 클래스를 사용하여 제품, 주문, 고객을 모델링합니다. 고객은 주문을 생성하고 주문에 제품을 추가한 후 주문을 확인합니다. 각 클래스는 객체 지향 프로그래밍의 다양한 개념을 활용하며, 관련된 데이터와 메서드를 함께 그룹화합니다.

728x90
반응형

'Javascript' 카테고리의 다른 글

Async Functions in Javascript  (0) 2024.04.01
OOP(4)  (0) 2023.11.06
OOP(3)  (0) 2023.11.05
OOP(2)  (0) 2023.11.05
OOP  (0) 2023.11.05