객체 지향 프로그래밍의 4가지 핵심 개념

MANG·2024년 6월 24일
post-thumbnail

자바스크립트에서 객체 지향 프로그래밍(OOP)의 4가지 핵심 개념, 즉 추상화(Abstraction), 캡슐화(Encapsulation), 상속(Inheritance), 다형성(Polymorphism)에 대해 알아보겠습니다.

1. 추상화(Abstraction)

객체 지향 프로그래밍에서 추상화는 객체를 설계하는 과정입니다. 이를 통해 객체의 내부 구현은 숨기고, 필요한 부분만을 외부에 공개합니다. 이는 사용자에게 복잡한 내부 구조를 숨기고, 객체 외부에 필요한 기능만을 노출시키는 것입니다.

class User {
  constructor(email, birthdate) {
    // 사용자의 이메일 주소
    this.email = email;
    // 사용자의 생일
    this.birthdate = birthdate;
  }

  // 물건 구매하기
  buy(item) {
    console.log(`${this.email} buys ${item.name}`);
  }
}

이렇게 하면 객체를 사용하는 사람은 내부 구조를 몰라도 emailbirthdate 프로퍼티와 buy 메소드를 통해 객체를 사용할 수 있습니다. 객체의 프로퍼티와 메소드를 잘 설계하고 문서화하면, 라이브러리나 프레임워크를 쉽게 사용할 수 있습니다.

2. 캡슐화(Encapsulation)

캡슐화는 객체의 프로퍼티나 메소드를 외부에서 직접 접근하지 못하도록 보호하는 것입니다. 이를 통해 객체의 상태를 안전하게 유지할 수 있습니다.

class User {
  constructor(email, birthdate) {
    this.email = email;
    this.birthdate = birthdate;
  }

  buy(item) {
    console.log(`${this.email} buys ${item.name}`);
  }

  get email() {
    return this._email;
  }

  set email(address) {
    if (address.includes('@')) {
      this._email = address;
    } else {
      throw new Error('invalid email address');
    }
  }
}

const user1 = new User('charlie123@google.com', '2000-12-05');
console.log(user1.email); // email이라는 getter 메소드 실행
user1.email = 'new123@google.com'; // email이라는 setter 메소드 실행

이렇게 하면 _email 프로퍼티를 직접 접근하지 못하고, email이라는 getter와 setter 메소드를 통해 접근하게 됩니다. 그러나 완벽한 캡슐화를 위해서는 클로저를 활용할 수 있습니다.

function createUser(email, birthdate) {
  let _email = email;

  const user = {
    birthdate,

    get email() {
      return _email;
    },

    set email(address) {
      if (address.includes('@')) {
        _email = address;
      } else {
        console.log('invalid email address');
      }
    },
  };

  return user;
}

const user1 = createUser('chris123@google.com', '19920321');
console.log(user1.email); // 'chris123@google.com'
console.log(user1._email); // undefined

3. 상속(Inheritance)

상속은 부모 클래스의 프로퍼티와 메소드를 자식 클래스가 물려받는 것입니다. 이를 통해 코드 재사용성을 높일 수 있습니다.

class User {
  constructor(email, birthdate) {
    this.email = email;
    this.birthdate = birthdate;
  }

  buy(item) {
    console.log(`${this.email} buys ${item.name}`);
  }
}

class PremiumUser extends User {
  constructor(email, birthdate, level) {
    super(email, birthdate);
    this.level = level;
  }

  streamMusicForFree() {
    console.log(`Free music streaming for ${this.email}`);
  }
}

PremiumUser 클래스는 User 클래스의 프로퍼티와 메소드를 상속받아 사용합니다. 이를 통해 코드 중복을 줄일 수 있습니다.

4. 다형성(Polymorphism)

다형성은 하나의 변수가 여러 종류의 객체를 가리킬 수 있는 것을 의미합니다. 이를 통해 다양한 객체를 같은 인터페이스로 다룰 수 있습니다.

class User {
  constructor(email, birthdate) {
    this.email = email;
    this.birthdate = birthdate;
  }

  buy(item) {
    console.log(`${this.email} buys ${item.name}`);
  }
}

class PremiumUser extends User {
  constructor(email, birthdate, level) {
    super(email, birthdate);
    this.level = level;
  }

  buy(item) {
    console.log(`${this.email} buys ${item.name} with a 5% discount`);
  }

  streamMusicForFree() {
    console.log(`Free music streaming for ${this.email}`);
  }
}

const item = {
  name: '스웨터',
  price: 30000,
};

const user1 = new User('chris123@google.com', '19920321');
const user2 = new User('rachel@google.com', '19880516');
const user3 = new User('brian@google.com', '20051125');
const pUser1 = new PremiumUser('niceguy@google.com', '19891207', 3);
const pUser2 = new PremiumUser('helloMike@google.com', '19900915', 2);
const pUser3 = new PremiumUser('aliceKim@google.com', '20010722', 5);

const users = [user1, pUser1, user2, pUser2, user3, pUser3];

users.forEach((user) => {
  user.buy(item);
});

이 코드를 보면 forEach 문 안에서 userUser 클래스로 만든 객체일 수도 있고, PremiumUser 클래스로 만든 객체일 수도 있습니다. 이처럼 다형성을 통해 다양한 객체를 동일한 인터페이스로 다룰 수 있습니다.

결론

객체 지향 프로그래밍의 핵심 개념인 추상화, 캡슐화, 상속, 다형성은 자바스크립트에서 객체 지향 프로그래밍을 이해하고 적용하는 데 매우 중요합니다. 이 개념들을 잘 이해하고 활용하면 보다 안정적이고 유지보수하기 쉬운 코드를 작성할 수 있습니다.

profile
대학생

0개의 댓글