Ruby (Rails) 프로그래머는 2 년 동안 Java를 사용하는 다른 팀으로 전환했습니다. 자바 빌더 패턴에 대해 몇 가지 질문이 있습니다.빌더 패턴 작동 방법
이 패턴을 사용하면 얻을 수있는 이점을 이해할 수 있습니다. 즉, 텔레 스코핑 생성자와 일관성없는 상태를 만드는 Java Bean Setter를 피하는 것이지만 정확히 어떻게 작동하는지 이해하는 데 어려움이 있습니다. 다음은 정확한 패턴입니다. 사용
public class Person
{
//why is it so important that this be final, hence immutable
private final String firstName;
private final String lastName;
// Constructor
public Person(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
//I have absolutely no idea what is this for and why is this necessary
public static Builder builder()
{
return new Builder();
}
//This is an inner class, where person is the outer class (the owning class)
//but why is this has to be a static class?
public static class Builder
{
private String firstName;
private String lastName;
public Builder withFirstName(String firstName)
{
//this.firstName refers to the Builder instance firstName
this.firstName = firstName;
return this;
//what is this return this? returning this instance of the Builder object?
}
public Builder withLastName(String lastName)
{
this.lastName = lastName;
return this;
}
public Person build()
{
return new Person(firstName, lastName);
//firstName and lastName here refer to the Builder's object instance vars,
//and used to create a new person object
}
}
}
를 사용하려면 :
이Person p = new Person.Builder(5).firstName("foo").lastName("bar").build();
1)에 대한 빌더에 PARAM "5"는 무엇입니까?
2) 빌더 내부 클래스가 정적 인 이유는 무엇입니까?
3) public static Builder builder() 메소드의 용도는 무엇입니까?
4) 우리는 실제로 새로운 내부 클래스를 작성하고 있음을 수정합니까?이 내부 클래스의 빌드 메소드가 새 Person 객체를 리턴하는 Builder 객체?
5)이 Person 클래스를 생성 한 것처럼 보입니다. 메모리 사용량을 두 배로 늘려야합니다. 하나는 외부 클래스 용이고 다른 하나는 내부 클래스 용입니다.
6) Person p = new Person ("foo", "bar")에 의해 새로운 person 객체를 만들 수 있다고 정정합니다.
7) 누군가가 어떻게 이것을 테스트합니까? 세터와 게터를 단위 테스트하는 방법?
8) 필드에서 유효성 검사를 수행 할 수 있습니까?
9) 필드가 필요하다는 것을 어떻게 지정해야합니까? 누군가 firstName만으로 빌드를 시도했지만 lastName이 제공되지 않은 경우 예외가 발생합니다.
미리 감사드립니다.
한 번 디자인 패턴을 읽으려고 시도 했습니까? 당신은 당신의 대답을 얻을 것입니다. – Lokesh
[wiki 기사] 읽기 (http://en.m.wikipedia.org/wiki/Builder_pattern) – Bohemian