728x90
인터페이스는 구현하지만 아무 일도 하지 않는 객체
null 참조 대신 알려진 인터페이스를 구현하는 구체적인 클래스의 인스턴스를 사용하여 달성됩니다.

- Gof의 디자인 패턴에는 없는 목록의 패턴이지만 자주 사용되는 디자인 패턴 기법이다.
- 구현이 매우 심플하며, 나름 중요한 의미가 있는 패턴
- 주의
- 이 패턴을 잘못 도입하면 예외나 에러를 탐지하기 어려워지는 경우가 있다.
- 도입했을 때 클래스와 코드가 마구 늘어난다면 이 패턴이 적절하지 않은 상황이거나 잘못 구현한 것이다.
- 인터페이스를 통해 관계를 느슨하게 만든 뒤, Null 객체를 만들어 null일 경우 해당 객체를 반환하는 것이다.
- Ex)

아무것도 하지 않는 객체를 생성해준다. 
Null처리가 필요한 문구가 - null 체크 코드는 흔한 관용구이지만, 읽기도 불편하고 실수하기도 쉽다는 문제가 있다.
- 만약 존재하지 않는 직원을 조회했을 때 null을 리턴하는 것이 아니라, Employee 인터페이스를 구현하면서 아무 일도 하지 않는 Employee 구현체 인스턴스를 리턴하게 하면 다음과 같이 null 체크 코드를 삭제할 수 있다

Null체크 필요 없어진다. 
인터페이스 내에 익명클래스로 선언하여도 된다. - 싱글 인스턴스를 보장
- Ex) 적용한 내코드

null 객체를 만들어 준다(static 으로 익명클래스로 만들어서 굳이 클래스를 생성하지 않아도 된다 -
@Entity @Getter @Builder @NoArgsConstructor(access = PROTECTED) @AllArgsConstructor(access = PRIVATE) public class CombinationStarRate extends BaseTimeEntity implements CombinationStarRateImpl { @Id @GeneratedValue @Column(name = "COMBINATION_STAR_RATE_ID") private Long id; private Integer starNumber; @ManyToOne(fetch = LAZY) @JoinColumn(name = "COMBINATION_ID") private Combination combination; @ManyToOne(fetch = LAZY) @JoinColumn(name = "MEMBER_ID") private Member member; @Override public void updateStarNumber(int starNumber) { this.starNumber = starNumber; } @Override public void addStarRate(Combination combination) { this.combination = combination; if(!combination.getCombinationStarRates().contains(this)){ combination.getCombinationStarRates().add(this); } } }
- NULL Object Pattern을 이용함으로써 Null을 체크하는 코드가 사라지게 된다.
https://www.geeksforgeeks.org/null-object-design-pattern/
Null object Design Pattern - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
https://johngrib.github.io/wiki/pattern/null-object/
널 오브젝트 패턴 (Null Object Pattern)
인터페이스는 구현하지만 아무 일도 하지 않는 객체
johngrib.github.io
728x90
'스터디 노트 > 잡것' 카테고리의 다른 글
| 채널 (0) | 2022.12.12 |
|---|---|
| Patch Null 체크 (0) | 2022.06.29 |
| 트러블 슈팅 (0) | 2022.05.11 |
| 프로젝트에 도움이 되는 URL (0) | 2022.05.02 |
| Exception (0) | 2021.12.26 |