IT책, 강의/리팩터링
11 - API 리팩터링 - 생성자를 팩터리 함수로 바꾸기
제로칼로리
2023. 9. 18. 22:15
개요
대부분의 객체 지향 언어에서 생성자는 객체를 초기화하는 특별한 용도의 함수다.
특별한 함수라 제약있는 경우가 있다. 자바의 경우 생성자는 반드시 자신의 인스턴스를 반환해야 한다. 서브클래스나 프락시를 반환할 수 없다. 생성자 이름도 클래스 이름으로 제한된다. 그리도 대부분의 언어에서 생성자 함수를 호출하기 위해 키워드가 필요하다(대게 new)
팩터리 함수에는 이런 제약이 없다.
예시
직원 유형을 다루는 예시
class Employee{ constructor(name, typeCode){ this._name = name; this.typeCode = typeCode; } get name(){return this._name;} get type(){ return Employee.legalTypeCodes[this._typeCode]; } static get legalTypeCodes(){ return {"E" : "Engineer","M":"Manager","S":"Salesperson"}; } } //클라이언트 const candidate = new Employee(document.name, document.empType); |
//가장 먼저 팩터리 함수 작성 function createEmployee(name, typeCode){ return new Employee(name,typeCode); } |
//클라이언트, 생성자 호출 코드 대체 const candidate = createEmployee(document.name, document.empType); |
//메서드 호출에 리터럴을 쓰는 것은 악취다 const candidate2 = createEmployee(document.name, 'E'); //팩터리 메서드 이름을 이용해 악취를 제거한다. function createEngineer(name){ return new Employee(name, "E"); } |
function createEmployee(name, typeCode){ return new Employee(name,typeCode); } class Employee{ constructor(name, typeCode){ this._name = name; this.typeCode = typeCode; } get name(){return this._name;} get type(){ return Employee.legalTypeCodes[this._typeCode]; } static get legalTypeCodes(){ return {"E" : "Engineer","M":"Manager","S":"Salesperson"}; } } //클라이언트, 생성자 호출 코드 대체 const candidate = createEmployee(document.name, document.empType); //메서드 호출에 리터럴을 쓰는 것은 악취다 const candidate2 = createEmployee(document.name, 'E'); //팩터리 메서드 이름을 이용해 악취를 제거한다. function createEngineer(name){ return new Employee(name, "E"); } |