Sobes.tech
Junior

Android-ის განვითარებაში Dagger-ს რა მიზნით იყენებენ?

sobes.tech AI

პასუხი AI-სგან

Dagger Android යෙදුම්වල අනුබද්ධතා (Dependency Injection - DI) ආවරණය සඳහා භාවිතා වේ.

Dagger භාවිතා කිරීමේ ප්‍රධාන වාසි:

  • අනුබද්ධතා අඩු කිරීම (Decoupling): වස්තු නිර්මාණය හා ඔවුන්ගේ භාවිතය වෙනම කරයි, කේතය වැඩි මොඩියුලර් හා පරීක්ෂා කිරීමට පහසු කරයි.
  • පරීක්ෂා කිරීමේ හැකියාව වැඩිදියුණු කිරීම: තනි කොටස් පරීක්ෂා කිරීමේදී mock හෝ stub පහසුවෙන් තැබිය හැක.
  • වස්තු ජීවිත චක්‍ර කළමනාකරණය: Dagger වස්තු නිර්මාණය හා නැවත භාවිතය කළමනාකරණය කරයි (උදාහරණයක් ලෙස, @Singleton, @Reusable, @ActivityScoped වැනි annotations සමඟ Dagger Android සඳහා).
  • වඩා පැහැදිලි dependency graph: Dagger කේතය ජනනය කරයි, එය කොම්පොනන්ට් එකිනෙකට කෙසේ අනුබද්ධවී ඇතිද පැහැදිලිව පෙන්වයි.
  • ආචාරික DI frameworks වලට වඩා වැඩි කාර්යක්ෂමතාව: Dagger කේතය සංයුතියේදී ජනනය කරයි, reflection වියදම් වලින් වැළකී සිටී.

Dagger හි මූලික අදහස්:

  • Modules (@Module): dependencies ලබා දේ. @Provides සමඟ ක්‍රම මගින් dependency එකක් කොහොම නිර්මාණය කරන්නේද කියා පෙන්වයි.
  • Components (@Component, @Subcomponent): modules හා dependencies ඉල්ලන classes අතර සම්බන්ධතා සකසයි. components මගින් injection කළ dependencies ලබා ගත හැක.
  • @Inject: constructors, fields, methods යන තැන්වල dependencies inject කිරීමට භාවිතා වේ.
  • Scope (@Scope): Dagger විසින් නිර්මාණය කරන වස්තු වල ජීවිත කාලය පාලනය කරයි.

උදාහරණයක් ලෙස, constructor මගින් dependency inject කිරීම:

// Dependency අවශ්‍ය class
public class MyPresenter {

    private final MyRepository repository;

    @Inject // Dagger මෙම constructor භාවිතා කරයි
    public MyPresenter(MyRepository repository) {
        this.repository = repository;
    }

    // ...
}

// Dependency class
public class MyRepository {
    // ...
}

// Module that provides MyRepository
@Module
public class AppModule {

    @Provides
    public MyRepository provideMyRepository() {
        return new MyRepository();
    }
}

// Component interface
@Component(modules = AppModule.class)
public interface AppComponent {
    void inject(MyActivity activity); // Activity තුළ injection සඳහා
}

සමස්තයෙන්, Dagger Android යෙදුම් වඩා සංවිධායක, පරීක්ෂා කළ හැකි හා නඩත්තු කළ හැකි බවට උදව් කරයි.