소개
- 새로운 인스턴스를 만드는 비용이 매우 클 때, 이미 존재하는 인스턴스를 복사하여 새로움 인스턴스를 만드는 방법이다.
- JAVA에서는 Cloneable 인터페이스를 받아서 clone 메서드를 구현할 수 있다. (얕은 복사)
- Cloneable 인터페이스는 얕은 복사를 지원하므로 참조형 자료의 경우에는 직접 clone 메서드 내부에서 복사하도록 하면 된다.
@Getter
@Setter
public class GithubIssue implements Cloneable {
private int id;
private String title;
private GihubRepository repository;
public GithubIssue(GithubRepository repository) {
this.repository = repository;
}
public String getUrl() {
return String.format("https://github.com/%s/%s/issues/%d",
repository.getUser(),
repository.getName(),
this.getId());
}
@Override
protected Override clone() throw CloneNotSupportedException {
GithubRepository repository = new GithubRepository();
repository.setUser(this.repository.getUser());
repository.setName(this.repository.getName());
GithubRepository githubIssue = new GithubIssue(repository);
githubIssue.setId(this.id);
githubIssue.setTitle(this.title);
return githubIssue;
}
}