기본적으로 만들어진 틀을 사용하는 것이다.
내용에서는 회원등록양식을 사용했는데 그 틀에 대한 기본틀을 프로토타입이라 하자. 여기서는 몸무게를 적지 않으면 60킬로를 기본값으로 넣는다고 한다.
그리고 중요한 것은 clone()메소드인데 왜 중요하냐면 기존에 만들어진 틀을 아주 쉽게 복사할 수 있는 것이다.
public class RegistrationForm implements Cloneable {
private String name = "Zed";
private String email = "zzzed@gmail.com";
private Date dateOfBirth = new Date(1990, 1, 28);
private int weight = 60;
private Gender gender = Gender.MALE;
private Status status = Status.SINGLE;
private List children = Arrays.asList(new Child(Gender.FEMALE));
private double monthSalary = 1000;
private List favouriteBrands = Arrays.asList("Adidas", "GAP");
@Override
protected RegistrationForm clone() throws CloneNotSupportedException {
RegistrationFrom prototyped = new RegistrationForm();
prototyped.name = name;
prototyped.email = email;
prototyped.dateOfBirth = (Date)dateOfBirth.clone();
prototyped.weight = weight;
prototyped.gender = gender
prototyped.status = status;
List childrenCopy = new ArrayList();
for (Child c : children) {
childrenCopy.add(c.clone());
}
prototyped.children = childrenCopy;
prototyped.monthsCopy = monthSalary;
List brandsCopy = new ArrayList();
for (String s : favoriteBrands) {
brandsCopy.add(s);
}
prototyped.favouriteBrands = brandsCopy;
return prototyped;
}
}
사용자를 만들 때마다, clone()을 호출해서 기본값으로 쓴다.왜 clone()을 사용해야 하나? 바로 자바가 나를 죽어라 헷갈리게 한 내용인 카피 문제이다.
이것 때문에 나는 getter를 만들때도 그것이 객체라면 복사를 한다. (혹시 몰라서...)
Clojure
(def registration-prototype
{:name "Zed"
:email "zzzed@gmail.com"
:date-of-birth "1970-01-01"
:weight 60
:gender :male
:status :single
:children [{:gender :female}]
:month-solary 1000
:brands ["Adidas" "GAP"]})
;;return new object
(assoc registration-prototype
:name "WHO"
:email "EMAIL@DOTCOM"
:weight 52
:gender :female
:month-salary 0)
clojure는 기본적으로 불변객체이기 때문에 clone은 필요없다. 그렇다면 항상 다 모든것을 final로 만들어 복사하면 느려지지 않을까?
느리긴 한데... 아주 느리지는 않다는 것이 클로저들의 주장인 것같다.
댓글 없음:
댓글 쓰기