간단하다... 론 패턴.. loan pattern


package com.javaTest.lamda;

public class Person {


public Person(String name, int age) {
this.name = name;
this.age = age;
}

public Person() {
}

String name;
int age;

public String getName() {
return name;
}

public Person setName(String name) {
this.name = name;
return this;
}

public int getAge() {
return age;
}

public Person setAge(int age) {
this.age = age;
return this;
}

@Override
public String toString() {
return "{name:"+this.name+",age:"+this.age+"}";
//return super.toString();
}

public int ageDifference(Person other) {
return age - other.age;
}
}

자 흔한 vo 인데... 잘보면 return this; 즉 자신을 리턴하고 있다. 객체를...


public void chaining001() {
Person person = new Person().setAge(10).setName("dr.who");

System.out.println(person.toString());
}


자.. 이렇게 체이닝이 만들어진다. 간단하지?


근데 문제는... 만약 vo 가 확장 vo 라면?

확장시 타입을 확실히 선언해주면된다. ( 참고 https://stackoverflow.com/questions/1069528/method-chaining-inheritance-don-t-play-well-together )


// XXX base 가 되는 클래스는 타입을 선언해줘야함
class Pet<T extends Pet>
{
private String name;
private String color;

public T setName(String name) {
this.name = name;
return (T) this;
}

public String getName() {
return name;
}

public String getColor() {
return color;
}

public T setColor(String color) {
this.color = color;
return (T) this;
}
}

// XXX 확장한 클래스는 베이스 클래스에게 타입을 알려줘야함(여기서는 Cat)
class Cat extends Pet<Cat>
{
private String sand;
private String hair;

public String getSand() {
return sand;
}

public Cat setSand(String sand) {
this.sand = sand;
return this;
}

public String getHair() {
return hair;
}

public Cat setHair(String hair) {
this.hair = hair;
return this;
}
}

class Dog extends Pet<Dog>
{
private String takeawalk;
private String vitality;

public String getTakeawalk() {
return takeawalk;
}

public Dog setTakeawalk(String takeawalk) {
this.takeawalk = takeawalk;
return this;
}

public String getVitality() {
return vitality;
}

public Dog setVitality(String vitality) {
this.vitality = vitality;
return this;
}
}

@Test
public void chaining001() {
Person person = new Person().setAge(10).setName("dr.who");

System.out.println(person.toString());


Cat cat = new Cat();
cat.setName("shasha").setHair("short").setSand("normal").setColor("mix");

Dog dog = new Dog();
dog.setName("jindol").setVitality("very good").setColor("brown").setTakeawalk("daily");
}



+ Recent posts