Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

Kuma's Curious Paradise

[cs] 노출식 모듈 패턴 본문

기술면접

[cs] 노출식 모듈 패턴

쿠마냥 2024. 8. 6. 10:19

Revealing Module Pattern : 모듈에서 노출하고 싶은 부분한 노출하는 패턴

  1. 자바 스크립트는 자바와 같은 클래스 기반 언어가 아니다.
  2. 자바에서 클래스와 메서드들은 각각 명시적인 접근 제어자를 가지지만 (public, private, protected, default), 자바 스크립트는 모든 함수와 변수가 전역적으로 접근이 가능하다.
  3. 이 경우, 분리(캡슐화)가 제대로 되어 있지 않아서 데이터의 무결성이 떨어지고 보안에 결함이 생긴다.
  4. 이를 해결하기 위해 노출 모듈 패턴이 등장했다.

 

예제1

const module1 = (() => {
  const privateFoo = () => {};
  const privateBar = [];

  const exported = {
    publicFoo: () => {},
    publicBar: () => {},
  };

  return exported; 
})();

console.log(module1);`

 

위의 예는 자바 스크립트의 노출 모듈 패턴 예시. 아래 주석을 달아 좀 더 자세히 설명하면

 

const module1 = (() => {
  // private 변수와 함수
  const privateFoo = () => {};
  const privateBar = [];

  // public 함수들을 담은 객체 exported
  const exported = {
    publicFoo: () => {},
    publicBar: () => {},
  };

  // exported 객체를 반환
  return exported;
})();

// module1을 로그로 출력
console.log(module1); // { publicFoo: [Function: publicFoo], publicBar: [Function: publicBar] }

 

console.log(module1)을 실행하면, module1 변수에 할당된 객체의 구조가 출력된다. toString을 자동으로 해 주는 듯.

 

 

예제2

const pukuba = (() => {
    const a = 1
    const b = () => 2
    const public = {
        c : 2, 
        d : () => 3
    }
    return public
})()
console.log(pukuba)
console.log(pukuba.a)
// { c: 2, d: [Function: d] }
// undefined

 

 

자바 예제

자바에서는 접근 제어자가 있기 때문에 이를 구현할 필요가 없다.

 

@Getter
@Setter
public class Bookshelf {
		
    private Long id;
    private List<Book> books;
    
		// 보이고 싶은 부분만 보이도록 1
    public Bookshelf() {
        this.books = new ArrayList<>();
    }

		// 보이고 싶은 부분만 보이도록 2
    public Long addBook(Book book) {
        this.books.add(book);
        return book.getId();
    }

}

 

@Getter // getter를 통해서 bookshelf에서 Book의 변수에 get...()로 접근 가능
@Setter
class Book {
    private Long id;
    private String title;
    private String author;

    public Book(Long id, String title, String author) {
        this.id = id;
        this.title = title;
        this.author = author;
    }
}