본문
170608(목) - DI with Dagger2
DI with Dagger2
http://kunny.github.io/life/2016/06/06/dagger2_resources/
How do we avoid the boilerplate that comes with the pattern?
1. 기존 소스
public calss Tweeter {
public void tweet(String tweet) {
TwitterApi api = new TwitterApi();
api.postTweet("신대규", tweet);
}
}
public class TwitterApi {
public void postTweet(String user, String tweet) {
OkHttpClient client = new OkHttpClient();
Request request = ...
client.newCall(request).execute();
}
}
Tweeter tweeter = new Tweeter();
tweeter.tweet("Hello, #Devoxx 2014!");
2. 개선
public class TwitterApi {
private final OkHttpClient client;
public TwitterApi(OkHttpClient client) {
this.client = client;
}
public void postTweet(String user, String tweet) {
OkHttpClient client = new OkHttpClient();
Request request = ...
client.newCall(request).execute();
}
}
public calss Tweeter {
private final TwitterApi api = new TwitterApi(new OkHttpClient());
private final String user;
public Tweeter(String user) {
this.user = user;
}
public void tweet(String tweet) {
api.postTweet(user, tweet);
}
}
Tweeter tweeter = new Tweeter("신대규");
tweeter.tweet("Hello, #Devoxx 2014!");
3. (more)기존코드
Timeline timeline = new Timeline("신대규");
timeline.loadMore(20);
for (Tweet tweet : timeline.get()) {
System.out.println(tweet);
}
public class Timeline() {
private final List<Tweet> cache = new ArrayList<>();
private final TwitterApi api = new TwitterApi(new OkHttpClient());
private final String user;
public Timeline(String user);
this.user = user;
}
public List<Tweet> get() {
...
}
public void loadMore(int amount) {
...
}
}
4. (more) 개선
public class Timeline() {
private final List<Tweet> cache = new ArrayList<>();
private final TwitterApi api = new TwitterApi(new OkHttpClient());;
private final String user;
public Timeline(TwitterApi api, String user);
this.api = api;
this.user = user;
}
public List<Tweet> get() {
...
}
public void loadMore(int amount) {
...
}
}
public calss Tweeter {
private final TwitterApi api = new TwitterApi(new OkHttpClient());;;
private final String user;
public Tweeter(TwitterApi api, String user) {
this.api = api;
this.user = user;
}
public void tweet(String tweet) {
api.postTweet(user, tweet);
}
}
OkHttpClient client = new OkHttpClient();
TwitterApi api = new TwitterApi(client);
String user = "신대규";
Tweeter tweeter = new Tweeter(api, user);
tweeter.tweet("Hello, #Devoxx 2014!");
Timeline timeline = new Timeline(api, user);
timeline.loadMore(20);
for (Tweet tweet : timeline.get()) {
System.out.println(tweet);
}
'Mobile > DI' 카테고리의 다른 글
170609(금) - DI with Dagger2 (0) | 2017.06.09 |
---|---|
170609(금) - DI with Dagger2 (0) | 2017.06.09 |
170609 (금) - DI with Dagger2 (0) | 2017.06.09 |
170608(목) - DI with Dagger2 (0) | 2017.06.08 |
170608(목) - DI with Dagger2 (0) | 2017.06.08 |
댓글