Sobes.tech
Middle

Ինչպես հեռացնել չորս կոնստրուկտորները անհատական ներկայացումում (CustomView):

sobes.tech AI

Պատասխան AI-ից

Մոդելային մեթոդ կամ builder pattern-ը կարող է օգտագործվել ուղղակի կոնստրուկտորների փոխարեն:

  • Մոդելային մեթոդ: Ինքնակառավարում է տեսքի օրինակները, ամփոփում է ստեղծման գործընթացը և թաքցնում է անհրաժեշտ կոնստրուկտորի ընտրության տրամաբանությունը:

    class MyCustomView private constructor(
        context: Context,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) : View(context, attrs, defStyleAttr, defStyleRes) {
    
        // Պատկան կոնստրուկտոր՝ ֆաբրիկային մեթոդների օգտագործման համար
    
        companion object {
            fun createDefault(context: Context): MyCustomView {
                // Նախնական կոնստրուկտորի համար սկզբնական տրամաբանություն
                return MyCustomView(context, null, 0, 0)
            }
    
            fun createFromAttrs(context: Context, attrs: AttributeSet?): MyCustomView {
                // Ատրիբուտներով սկզբնական տրամաբանություն
                return MyCustomView(context, attrs, 0, 0)
            }
    
            // Ավելին՝ ֆաբրիկային մեթոդներ այլ կոնստրուկտորների համար
        }
    }
    
  • Builder pattern: Օգտակար է, երբ կոնստրուկտորների քանակը շատ է կամ ունեն շատ ընտրական պարամետրեր: Հնարավոր է քայլ առ քայլ ստեղծել տեսքի օբյեկտը:

    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) {
    
        // Պատկան կոնստրուկտոր
    
        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 {
                // Ստեղծման և սկզբնավորման տրամաբանություն
                return MyCustomView(context, attrs, defStyleAttr, defStyleRes)
            }
        }
    }
    
    // Օգտագործում builder-ը
    val myView = MyCustomView.Builder(context)
        .setAttrs(attrs)
        .build()
    

Ընտրությունը՝ ֆաբրիկային մեթոդ կամ builder pattern, կախված է տեսքի սկզբնավորման բարդությունից: Պարզ դեպքերում բավարար է ֆաբրիկային մեթոդները, իսկ բարդ դեպքերում՝ builder-ը։