Skip to content

Instantly share code, notes, and snippets.

@wataru420
Created September 25, 2012 11:09
Show Gist options
  • Save wataru420/3781181 to your computer and use it in GitHub Desktop.
Save wataru420/3781181 to your computer and use it in GitHub Desktop.
チェーンメソッド風な実装
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
*/
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);
}
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);
}
}
@wataru420
Copy link
Author

APIの呼び出しとかでこんな風にしたらチェーンメソッドっぽく呼べてオーバーロードよりいいなーって思ったんだけどどうだろう。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment