Upgrade to PRO for Only $50/Year—Limited-Time Offer! 🔥

Android: Daggear2でDI

Android: Daggear2でDI

Sato Shun

May 13, 2015
Tweet

More Decks by Sato Shun

Other Decks in Programming

Transcript

  1. DIͱ͸? ίʔυྫ class Blogger { public void post(String title) {

    // Կ͔ϝΠϯͷॲཧ // ... // fileʹlogΛऔΔ FileLogger logger = new FileLogger(“log.txt”); logger.logging(); } }
  2. DIͱ͸? ίʔυྫ class Blogger { public void post(String title) {

    // Կ͔ϝΠϯͷॲཧ // ... // fileʹlogΛऔΔ FileLogger logger = new FileLogger(“log.txt”); logger.logging(); } }
  3. DIͱ͸? ίʔυྫ class Blogger { FileLogger logger = new FileLogger(“log.txt”);

    public void post(String title) { // Կ͔ϝΠϯͷॲཧ // ... // fileʹlogΛऔΔ logger.logging(); } }
  4. DIͱ͸? ίʔυྫ class Blogger { FileLogger logger; public Blogger(FileLogger logger)

    { this.logger = logger; } public void post(String title) { // Կ͔ϝΠϯͷॲཧ // ... // fileʹlogΛऔΔ logger.logging(); } }
  5. DIͱ͸? ίʔυྫ class Blogger { FileLogger logger; public Blogger(FileLogger logger)

    { this.logger = logger; } public void post(String title) { // Կ͔ϝΠϯͷॲཧ // ... // fileʹlogΛऔΔ logger.logging(); } } logger = new FileLogger(“log”); blogger = new Blogger(logger); blogger.post(“Hello World”); ֎෦͔Β ґଘΛ஫ೖ
  6. Dagger2ͷجຊతͳ࢖͍ํ public class MainActivity extends ActionBarActivity { SharedPreferences mSharedPreferences; Gson

    gson; @Override protected void onCreate(Bundle saved) { mSharedPreferences = getSharedPreferences("app", Context.MODE_PRIVATE) gson = new GsonBuilder() .setFieldNamingPolicy( LOWER_CASE_WITH_UNDERSCORES) .create(); } }
  7. Dagger2: Moduleฤ @Module public class ApplicationModule { private final AndroidApplication

    application; public ApplicationModule(AndroidApplication application) { this.application = application; } @Provides Context provideContext() { return application; } @Provides @Singleton SharedPreferences provideSharedPreferences(Context context) { return context.getSharedPreferences("app", Context.MODE_PRIVATE); } } provideContextϝιου͔Β ࣗಈతʹҾ਺͕౉͞ΕΔ
  8. Dagger2: Moduleฤ @Module public class DataModule { @Provides @Singleton Gson

    provideGson() { return new GsonBuilder() .setFieldNamingPolicy( LOWER_CASE_WITH_UNDERSCORES) .create(); } }
  9. Dagger2: Componentฤ @Singleton @Component(modules = { ApplicationModule.class, DataModule.class }) public

    interface ApplicationComponent { void inject(MainActivity activity); } ΫϥεͰ࢖͍͍ͨModuleΛ Componentʹ·ͱΊΔ
  10. Dagger2: جຊ׬੒ public class MainActivity extends ActionBarActivity { @Inject SharedPreferences

    mSharedPreferences; @Inject Gson gson; … } ઌ΄ͲModuleͰఆٛ ͨ͠Πϯελϯε͕ Inject͞ΕΔ!