CS Study/디자인패턴
2021.12.11_데코레이터패턴02.패턴적용하기
KyeongMin
2021. 12. 11. 15:02
728x90
반응형
CommentService
public interface CommentService
{
void addComment(String comment);
}
- 코멘트를 추가한 인터페이스 하나 추가
DefaultCommentService
public class DefaultCommentService implement 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);
}
}
- 감싸는 데코레이터 생성
TrimmingCommentDecorator
public class TrimmingCommentDecorator extends CommentDecoorator{
public TrimmingCommentDecorator(CommentService commentService){
super(commentService);
}
@Override
public void addComment(String comment){
super.addComment(trim(comment));
}
private String trim(String comment){
return comment.replace("...", "");
}
}
SpanFilteringCommentDecorator
public class SpanFilteringCommentDecorator extends CommentDecorator{
public SpanFilteringCommentDevorator(CommentService commentService){
super.(commentService)
}
@Override
public void addComment(String comment){
if(isNotSpan(comment)){
super.addComment(comment);
}
}
private boolean isNotSpan(String comment){
return !comment.contains("http");
}
}
Client
public class Client{
private CommentService commentService{
this.CommentService = commentService;
}
public void writeComment(String comment){
commentService.addComment(comment);
}
}
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");
}
}
- 이렇게 DefaultCommentService로만 받지만 여러 기능을 추가 할 수 있음
- 기능 구현이 추가 될때 좀 유용하게 쓸 수 있음
- 상속과의 다른점은 현재는 두개 의 기능이 있는데 내가 두개의 기능을 다 검사하고 싶을때
- 상속의 경우는 통합된 한개를 더 만들어야하지만
- 데코레이터를 이용하면 그렇게 하지 않아도 가능함
728x90
반응형