Development/Java
java - 메서드 체인닝(Method chaining)
linuxism
2012. 10. 8. 14:09
Method chaining - Wikipidea : http://en.wikipedia.org/wiki/Method_chaining
자바 7에 추가될뻔한 기능이었다고 한다. ^^; 자바의 빈클래스에 막 길들어지기 시작한 내게는 조금 낯선 형태랄까?
setter 메소드에서 클래스(this)를 리턴해주는 형태니까...
Chaining.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | public class DateChaining { private String year; private String month; private String day; public String getMonth() { return month; } public DateChaining setMonth(String month) { this .month = month; return this ; } public String getDay() { return day; } public DateChaining setDay(String day) { this .day = day; return this ; } public String getYear() { return year; } public DateChaining setYear(String year) { this .year = year; return this ; } @Override public String toString() { return "DateChaining [year=" + year + ", month=" + month + ", day=" + day + "]" ; } } |
ChainingTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | package test; import main.DateChaining; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.junit.Test; public class ChainingTest { @Test public void 체이닝_테스트() { //given DateChaining chain = new DateChaining(); //when chain.setYear( "2011" ).setMonth( "07" ).setDay( "17" ); //then assertThat(chain.getYear(), is( "2011" )); assertThat(chain.getMonth(), is( "07" )); assertThat(chain.getDay(), is( "17" )); } @Test public void 순서흐트러진_체이닝_테스트() { //given DateChaining chain = new DateChaining(); //when chain.setMonth( "07" ).setDay( "17" ).setYear( "2011" ); //then assertThat(chain.getYear(), is( "2011" )); assertThat(chain.getMonth(), is( "07" )); assertThat(chain.getDay(), is( "17" )); } @Test public void 중복된_필드에대한_세트선언시() { //given DateChaining chain = new DateChaining(); //when // chain.setYear( "2011" ).setMonth( "07" ).setDay( "17" ).setYear( "2012" ); //then assertNotSame(chain.getYear(), is( "2011" )); assertThat(chain.getMonth(), is( "07" )); assertThat(chain.getDay(), is( "17" )); } } |
출처 - http://java.ihoney.pe.kr/175