Skip to content

Latest commit

 

History

History
93 lines (69 loc) · 2.96 KB

File metadata and controls

93 lines (69 loc) · 2.96 KB

2021.12.11_데코레이터패턴01.패턴소개

  • 기존에 있는 코드를 변경하지 않고 부가적인 기능 추가할 수 있는 구조적인 패턴
  • 원하는 부가 기능 런타임에 다이나믹 하게 추가
    • 스태틱하게 컴파일 타임에 아니구....(정적)
    • 유연하게 라면 런타임에 변경 할 수 있음
    • 런타임의 기본을 확장하는 개념임

코드

pulic class Client{
    private Client(CommentService);
    
    public Client (CommentService commentService){
        this.CommentService = commentService;
    }
    
    private void writeComment(String comment){
		Comment.Service.addComment(comment);
    }
    
    publiv static void main(String[] args){
		Client client = new Client(new CommentService);
        client.WriteComment("오징어게임");
        client.writeComment("보는게 하는거 보다 재밌을 수 없음");
    }
}

CommentService

public void addComment(String comment){
    System.out.println(comment);
}
  • 출력하기 전에 트리밍하고 싶다면
  • 새로운 클래스를 만들면됨

TrimmingCommentService

public class TrimmingCommentService extends CommentService{
    @Override
    public void addComment(String comment){
		super.addComment(trim(comment));
    }
    
    private String trim(String comment){
		return comment.replace("...");
    }
}
  • 위와 같이 서비스를 하나 생성을 하고 나서 아래와 같이 클라이언트 코드 변경

Client 코드 변경

pulic class Client{
    private Client(CommentService);
    
    public Client (CommentService commentService){
        this.CommentService = commentService;
    }
    
    private void writeComment(String comment){
		Comment.Service.addComment(comment);
    }
    
    publiv static void main(String[] args){
		Client client = new Client(new TrimmingCommentService();
        client.WriteComment("오징어게임");
        client.writeComment("보는게 하는거 보다 재밌을 수 없음");
    }
} 
  • 기존의 코드 변경 없이 그대로 쓸 수 있지만

  • 상속을 써야하고 복잡하고 결정적으로 유연하다고 볼 수 없음

  • 또 어떤 경우를 생성할때 또 다시 해야하고 두개를 한번에 쓰고 싶다면 또 합쳐진것을 만들어야하는 상황이 생긴다. 결국 계속 확장해 나가기가 쉽지 않음

image-20211211135156199

  • Component 라는 역할을 하는 인터페이스가 있음

  • ConcreateComponent와 Decorator가 둘다 구현한 인터페이스고 같은 오퍼레이션을 가지고 잇음

    • 여기까지 보게 되면 컴포짓 패턴과 유사하지만 데코레이터가 컴포짓패턴에 있던 여러개의 데코레이터를 가지고 있는 것이 아니고, 딱하나의 wrappee라는 하나의 컴포넌트만 가지고 호출한다.
  • 그리고 Concreate Decorator로 각 기능을 구현해서 사용