Middle
Jak usunąć cztery konstruktory w niestandardowym widoku (CustomView)?
sobes.tech AI
Odpowiedź od AI
Możesz użyć metody fabrycznej lub wzorca builder zamiast bezpośredniego korzystania z konstruktorów.
-
Metoda fabryczna: Umożliwia tworzenie instancji widoku, abstrahując proces tworzenia i ukrywając logikę wyboru odpowiedniego konstruktora.
class MyCustomView private constructor( context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int ) : View(context, attrs, defStyleAttr, defStyleRes) { // Prywatny konstruktor, aby wymusić korzystanie z metod fabrycznych companion object { fun createDefault(context: Context): MyCustomView { // Logika inicjalizacji dla domyślnego konstruktora return MyCustomView(context, null, 0, 0) } fun createFromAttrs(context: Context, attrs: AttributeSet?): MyCustomView { // Logika inicjalizacji z atrybutami return MyCustomView(context, attrs, 0, 0) } // Dodatkowe metody fabryczne dla innych kombinacji konstruktorów } } -
Wzorzec builder: Przydatny, gdy jest wiele konstruktorów lub mają wiele opcjonalnych parametrów. Pozwala na stopniowe tworzenie obiektu.
class MyCustomView private constructor( private val context: Context, private val attrs: AttributeSet?, private val defStyleAttr: Int, private val defStyleRes: Int ) : View(context, attrs, defStyleAttr, defStyleRes) { // Prywatny konstruktor class Builder(private val context: Context) { private var attrs: AttributeSet? = null private var defStyleAttr: Int = 0 private var defStyleRes: Int = 0 fun setAttrs(attrs: AttributeSet?) = apply { this.attrs = attrs } fun setDefStyleAttr(defStyleAttr: Int) = apply { this.defStyleAttr = defStyleAttr } fun setDefStyleRes(defStyleRes: Int) = apply { this.defStyleRes = defStyleRes } fun build(): MyCustomView { // Logika tworzenia i inicjalizacji widoku na podstawie parametrów return MyCustomView(context, attrs, defStyleAttr, defStyleRes) } } } // Użycie buildera val myView = MyCustomView.Builder(context) .setAttrs(attrs) .build()
Wybór między metodą fabryczną a wzorcem builder zależy od złożoności inicjalizacji widoku. Dla prostszych przypadków wystarczą metody fabryczne. Dla bardziej złożonych z wieloma opcjami, lepszy jest wzorzec builder.