Created
September 25, 2012 11:09
-
-
Save wataru420/3781181 to your computer and use it in GitHub Desktop.
チェーンメソッド風な実装
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Main { | |
public static void main(String[] args) { | |
Timeline timeline = new TimelineImpl(); | |
//チェーンメソッドで色々できます。 | |
timeline.postList(777).limit(15).offset(100).get(); | |
timeline.postList(55).get(); | |
} | |
} | |
/* 結果 | |
timelineId=777 limit=15 offset=100 | |
timelineId=55 limit=10 offset=0 | |
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface Timeline { | |
public interface Posts { | |
//limitを設定できます | |
public Posts limit(int limit); | |
//offsetを設定できます | |
public Posts offset(int offset); | |
//getが呼ばれるとDao等にアクセスしてデータを取得します。 | |
public List<Post> get(); | |
} | |
//取得対象のIDをセットします。 | |
Posts postList(int timelineId); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TimelineImpl implements Timeline { | |
public static class Posts implements Timeline.Posts { | |
private final int timelineId; | |
private int limit = 10; | |
private int offset = 0; | |
public Posts(int timelineId) { | |
this.timelineId = timelineId; | |
} | |
@Override | |
public Timeline.Posts limit(int limit) { | |
this.limit = limit; | |
return this; | |
} | |
@Override | |
public Timeline.Posts offset(int offset) { | |
this.offset = offset; | |
return this; | |
} | |
@Override | |
public List<Post> get() { | |
System.out.println("timelineId=" + timelineId + " limit=" + limit + " offset=" + offset); | |
return null;//ここでゴニョゴニョして返す | |
} | |
} | |
@Override | |
public Posts postList(int timelineId) { | |
//インスタンスの生成コストが気になるところ | |
return new Posts(timelineId); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
APIの呼び出しとかでこんな風にしたらチェーンメソッドっぽく呼べてオーバーロードよりいいなーって思ったんだけどどうだろう。