EJ2E Item 1. 생성자 대신 static 팩토리 메소드 사용을 고려하라.
Java : 2008/10/27 17:52
참조: Effective Java 2nd Edition. Item 1: Consider static factory methods instead of constructor
static factory method는 Factory Method 디자인 패턴이랑 같은 것이 아니다. 직접적인 관계는 없다.
장점
- 이름을 가질 수 있다.
- 매번 새로운 객체를 만들 필요가 없어진다.
- 하위 타입을 반환할 수 있다. -> service provider framework
- 타입 매개변수를 가진 클래스 객체를 생성할 때 간결하게 쓸 수 있다. -> type inference
Service Provider Framework
- Servide interface: 공급자가 구현할 인터페이스. ex) Connection
- Provider registration API: 시스템이 구현체를 등록할 때 사용. ex) DriverManager.registerDriver
- Service access API: 사용자가 서비스 객체를 얻어올 때 사용. == fexible static factory. ex) DriverManager.getConnection
- (option) Service provider interface: 공급자가 서비스 구현체의 객체를 생성할 때 구현한다. ex) Driver
단점
- public 또는 protected 생성자 없이 static factory method만 제공하는 클래스는 상속할 수 없다.
- 다른 static factory method랑 확연하게 구분이 안 된다. -> 이름을 잘 짓자.(valueOf, of, getInstance, newInstance, getType, newType)
static factory method는 Factory Method 디자인 패턴이랑 같은 것이 아니다. 직접적인 관계는 없다.
장점
- 이름을 가질 수 있다.
- 매번 새로운 객체를 만들 필요가 없어진다.
- 하위 타입을 반환할 수 있다. -> service provider framework
- 타입 매개변수를 가진 클래스 객체를 생성할 때 간결하게 쓸 수 있다. -> type inference
Service Provider Framework
- Servide interface: 공급자가 구현할 인터페이스. ex) Connection
- Provider registration API: 시스템이 구현체를 등록할 때 사용. ex) DriverManager.registerDriver
- Service access API: 사용자가 서비스 객체를 얻어올 때 사용. == fexible static factory. ex) DriverManager.getConnection
- (option) Service provider interface: 공급자가 서비스 구현체의 객체를 생성할 때 구현한다. ex) Driver
단점
- public 또는 protected 생성자 없이 static factory method만 제공하는 클래스는 상속할 수 없다.
- 다른 static factory method랑 확연하게 구분이 안 된다. -> 이름을 잘 짓자.(valueOf, of, getInstance, newInstance, getType, newType)
'Java' 카테고리의 다른 글
| EJ2E Item 6. 사용하지 않는 객체 레퍼런스를 제거하라 (0) | 2008/10/28 |
|---|---|
| EJ2E Item 5. 불필요한 객체 생성 방지하기 (0) | 2008/10/28 |
| EJ2E Item 4. private 생성자로 객체생성 방지하기 (0) | 2008/10/28 |
| EJ2E Item 3. 싱글톤 속성은 private 성성자 또는 enum 타입으로 (2) | 2008/10/28 |
| EJ2E Item 2. 생성자에 매개변수가 너무 많을 때는 빌더를 고려하자. (0) | 2008/10/27 |
| EJ2E Item 1. 생성자 대신 static 팩토리 메소드 사용을 고려하라. (0) | 2008/10/27 |
| Effective Java Reloaded (0) | 2008/10/26 |
| ReadWriteLock 인터페이스 (0) | 2008/09/25 |
| Generic 팩토리 메소드 (2) | 2008/09/25 |
| 자바의 숨겨진 기능들 (6) | 2008/09/22 |
| this.new XXX()를 쓰는 이유가 뭘까? (2) | 2008/08/21 |





