12.1 웹 애플리케이션에서 사용자 관리
JavaScript의 객체 지향 프로그래밍(OOP)은 복잡하고 확장 가능하며 유지보수가 쉬운 애플리케이션을 만들 수 있게 해줘. JavaScript에서 클래스, 상속, 캡슐화, 다형성을 사용하는 몇 가지 실전 예제를 살펴보자.
사용자 관리를 위한 웹 애플리케이션을 개발한다고 가정해보자. 상속을 사용하여 User
, Admin
, Guest
와 같은 다양한 사용자 유형에 대한 클래스를 만들 수 있어.
설명:
User
클래스는login
과logout
메소드를 포함한다Admin
클래스는User
를 상속받아deleteUser
메소드를 추가한다Guest
클래스는User
를 상속받아requestAccess
메소드를 추가한다Admin
과Guest
클래스의 인스턴스는 자신과 기본 클래스의 메소드를 사용한다
코드:
JavaScript
class User {
constructor(username, email) {
this.username = username;
this.email = email;
}
login() {
console.log(`${this.username} logged in.`);
}
logout() {
console.log(`${this.username} logged out.`);
}
}
class Admin extends User {
constructor(username, email) {
super(username, email);
this.role = 'admin';
}
deleteUser(user) {
console.log(`${this.username} deleted user ${user.username}.`);
}
}
class Guest extends User {
constructor(username, email) {
super(username, email);
this.role = 'guest';
}
requestAccess() {
console.log(`${this.username} requested access.`);
}
}
const admin = new Admin('adminUser', 'admin@example.com');
const guest = new Guest('guestUser', 'guest@example.com');
admin.login(); // "adminUser logged in."
admin.deleteUser(guest); // "adminUser deleted user guestUser."
admin.logout(); // "adminUser logged out."
guest.login(); // "guestUser logged in."
guest.requestAccess(); // "guestUser requested access."
guest.logout(); // "guestUser logged out."
12.2 온라인 쇼핑몰의 상품 관리
이번 예제에서는 Product
, Electronics
, Clothing
과 같은 온라인 쇼핑몰의 다양한 유형의 상품을 나타내는 클래스를 생성할 거야. 또한 calculateDiscount
메소드에 대한 다형성을 구현할 거야.
설명:
Product
클래스는 기본적으로 10% 할인을 계산하는calculateDiscount
메소드를 포함한다Electronics
클래스는calculateDiscount
메소드를 재정의하여 전자 제품에 대해 20% 할인을 제공한다Clothing
클래스는calculateDiscount
메소드를 재정의하여 의류에 대해 15% 할인을 제공한다Electronics
와Clothing
클래스의 인스턴스는 할인 계산을 위한 자신의calculateDiscount
메소드를 사용한다
코드:
JavaScript
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
calculateDiscount() {
return this.price * 0.1; // 기본 10% 할인
}
display() {
console.log(`${this.name} - $${this.price.toFixed(2)}`);
}
}
class Electronics extends Product {
constructor(name, price, brand) {
super(name, price);
this.brand = brand;
}
calculateDiscount() {
return this.price * 0.2; // 전자 제품에 대해 20% 할인
}
}
class Clothing extends Product {
constructor(name, price, size) {
super(name, price);
this.size = size;
}
calculateDiscount() {
return this.price * 0.15; // 의류에 대해 15% 할인
}
}
const laptop = new Electronics('Laptop', 1000, 'BrandX');
const tshirt = new Clothing('T-Shirt', 20, 'M');
laptop.display(); // "Laptop - $1000.00"
console.log(`Discount: $${laptop.calculateDiscount().toFixed(2)}`); // "Discount: $200.00"
tshirt.display(); // "T-Shirt - $20.00"
console.log(`Discount: $${tshirt.calculateDiscount().toFixed(2)}`); // "Discount: $3.00"
12.3: 도서관 관리
이번 예제에서는 Book
, Magazine
, Library
클래스를 포함한 도서관 관리를 위한 클래스를 생성할 거야. 도서관에서 항목을 추가 및 삭제하기 위한 메소드도 구현할 거야.
설명:
Book
및Magazine
클래스는LibraryItem
클래스를 상속받아display
메소드를 재정의한다Library
클래스는addItem
,removeItem
,displayItems
메소드를 제공하여 도서관 컬렉션을 관리한다Book
및Magazine
클래스의 인스턴스는 도서관에 추가 및 제거되며,display
메소드를 사용하여 정보가 표시된다
코드:
JavaScript
class LibraryItem {
constructor(title, year) {
this.title = title;
this.year = year;
}
display() {
console.log(`${this.title} (${this.year})`);
}
}
class Book extends LibraryItem {
constructor(title, year, author) {
super(title, year);
this.author = author;
}
display() {
console.log(`${this.title} by ${this.author} (${this.year})`);
}
}
class Magazine extends LibraryItem {
constructor(title, year, issueNumber) {
super(title, year);
this.issueNumber = issueNumber;
}
display() {
console.log(`${this.title} - Issue ${this.issueNumber} (${this.year})`);
}
}
class Library {
constructor() {
this.items = [];
}
addItem(item) {
this.items.push(item);
console.log(`Added: ${item.title}`);
}
removeItem(title) {
this.items = this.items.filter(item => item.title !== title);
console.log(`Removed: ${title}`);
}
displayItems() {
this.items.forEach(item => item.display());
}
}
const library = new Library();
const book = new Book('JavaScript: The Good Parts', 2008, 'Douglas Crockford');
const magazine = new Magazine('JavaScript Weekly', 2021, 450);
library.addItem(book); // "Added: JavaScript: The Good Parts"
library.addItem(magazine); // "Added: JavaScript Weekly"
library.displayItems();
// "JavaScript: The Good Parts by Douglas Crockford (2008)"
// "JavaScript Weekly - Issue 450 (2021)"
library.removeItem('JavaScript Weekly'); // "Removed: JavaScript Weekly"
library.displayItems(); // "JavaScript: The Good Parts by Douglas Crockford (2008)"
GO TO FULL VERSION