Sobes.tech
Middle

Kas saak anda näite, millal Androidi raamistik kasutab 'Fabrika' disainimustrit?

sobes.tech AI

Vastus AI-lt

// Näited Factory Method kasutamisest Androidis
// View loomine XML-malli kaudu
// LayoutInflater on Factory Method rakendus
LayoutInflater inflater = LayoutInflater.from(context);
View rootView = inflater.inflate(R.layout.my_layout, parent, false);

// Intent loomine
// Intent konstruktor toimib kui Abstract Factory, mis loob ComponentName objekte
Intent serviceIntent = new Intent(context, MyService.class);

// Context - abstraktne tehas süsteemiteenuste kasutamiseks
// LayoutInflater saamine Contextist
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

// NotificationManager saamine Contextist
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

Näide võiks olla LayoutInflater. See varjab üksikasju, kuidas luua konkreetsed View-i objektid XML-failidest. Me lihtsalt edastame mallide ressursi ja saame valmis View või View hierarhia. LayoutInflater toimib kui tehas, luues erinevat tüüpi esitlusi (TextView, ImageView, Button jne) XML-tägide põhjal.

Teine näide — Intent-ide loomine. Intent konstruktorit võib vaadata kui osa tehase meetodist, mis loob abstraktse objekti, mis esindab tegevust, mida tuleb teha.

Context toimib samuti kui abstraktne tehas, pakkudes juurdepääsu erinevatele süsteemiteenustele (LayoutInflater, NotificationManager, PackageManager), mis luuakse ja pakutakse vastavalt nõudmisele.

<!-- XML-malli näide, mida töötab LayoutInflater -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/myTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tere, maailm!" />

    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Vajuta mind" />

</LinearLayout>

Seega kasutab Android raamistik aktiivselt "Fabrika" musteril põhinevat lähenemist erinevatel abstraktsiooni tasemetel, et lihtsustada ja dekomponeerida objektide loomist.