728x90
반응형
Decorator Pattern
기존 코드를 변경하지 않고 부가 기능을 추가하는 패턴
상속이 아닌 위임을 사용해서 보다 유연하게 (런타임에) 부가 기능을 추가하는 것도 가능
기존 코드를 변경하지 않고 부가 기능을 추가하는 패턴
Client
public class Client {
private CommentService commentService;
public Client(CommentService commentService) {
this.commentService = commentService;
}
public void writeComment(String comment) {
commentService.addComment(comment);
}
}
CommentService
public interface CommentService {
void addComment(String comment);
}
DefaultCommentService
public class DefaultCommentService implements CommentService {
@Override
public void addComment(String comment) {
System.out.println(comment);
}
}
CommentDecorator
public class CommentDecorator implements CommentService {
private CommentService commentService;
public CommentDecorator(CommentService commentService) {
this.commentService = commentService;
}
@Override
public void addComment(String comment) {
commentService.addComment(comment);
}
}
SpamFilteringCoimmentDecorator
public class SpamFilteringCommentDecorator extends CommentDecorator {
public SpamFilteringCommentDecorator(CommentService commentService) {
super(commentService);
}
@Override
public void addComment(String comment) {
if (isNotSpam(comment)) {
super.addComment(comment);
}
}
private boolean isNotSpam(String comment) {
return !comment.contains("http");
}
}
TrimCommentDecorator
public class TrimmingCommentDecorator extends CommentDecorator {
public TrimmingCommentDecorator(CommentService commentService) {
super(commentService);
}
@Override
public void addComment(String comment) {
super.addComment(trim(comment));
}
private String trim(String comment) {
return comment.replace("...", "");
}
}
App
public class App {
private static boolean enabledSpamFilter = true;
private static boolean enabledTrimming = true;
public static void main(String[] args) {
CommentService commentService = new DefaultCommentService();
if (enabledSpamFilter) {
commentService = new SpamFilteringCommentDecorator(commentService);
}
if (enabledTrimming) {
commentService = new TrimmingCommentDecorator(commentService);
}
Client client = new Client(commentService);
client.writeComment("오징어게임");
client.writeComment("보는게 하는거 보다 재밌을 수가 없지...");
client.writeComment("http://whiteship.me");
}
}
[패턴 복습]
장점 | 단점 |
- 새로운 클래스를 만들지 않고 기존 기능을 조합할 수 있다. - 컴파일 타임이 아닌 런타임에 동적으로 기능을 변경할 수 있다. |
- 데코레이터를 조합하는 코드가 복잡할 수 있다. |
[실무에서 쓰이는 경우]
- 자바
- InputStream, OutputStream, Reader, Writer의 생성자를 활용한 랩퍼
- java.util.Collections 가 제공하는 메소드를 활용한 랩퍼
- javax.servlet.http.HttpServletRequest/ResponseWrapper
- 스프링
- ServerHttpRequestDecorator
728x90
반응형
'Design Patterns > 구조(Structural)' 카테고리의 다른 글
[Flyweight]플라이웨이트패턴 (0) | 2022.10.18 |
---|---|
[Facade]퍼사드패턴 (0) | 2022.10.18 |
[Composite]컴포짓패턴 (0) | 2022.08.01 |
[Bridge]브릿지패턴 (0) | 2022.08.01 |
[Adaptor]어댑터패턴 (0) | 2022.05.31 |