Android 設計模式之原型模式

來源:互聯網
上載者:User

標籤:

簡介:在系統中要建立大量的對象,這些對象之間具有幾乎完全相同的功能,只是在細節上有一點兒差別

用原型執行個體指定建立對象的種類,並且通過拷貝這些原型建立新的對象   

example 1:

我們需要一張Bitmap的幾種不同格式:ARGB_8888、RGB_565、ARGB_4444、ALAPHA_8等。那我們就可以先建立一個ARGB_8888的Bitmap作為原型,在它的基礎上,通過調用Bitmap.copy(Config)來建立出其它幾種格式的Bitmap

  /**     * Tries to make a new bitmap based on the dimensions of this bitmap,     * setting the new bitmap‘s config to the one specified, and then copying     * this bitmap‘s pixels into the new bitmap. If the conversion is not     * supported, or the allocator fails, then this returns NULL.  The returned     * bitmap initially has the same density as the original.     *     * @param config    The desired config for the resulting bitmap     * @param isMutable True if the resulting bitmap should be mutable (i.e.     *                  its pixels can be modified)     * @return the new bitmap, or null if the copy could not be made.     */    public Bitmap copy(Config config, boolean isMutable) {        checkRecycled("Can‘t copy a recycled bitmap");        Bitmap b = nativeCopy(mNativeBitmap, config.nativeInt, isMutable);        if (b != null) {            b.setPremultiplied(mRequestPremultiplied);            b.mDensity = mDensity;        }        return b;    }

另外一個例子就是Java中所有對象都有的一個名字叫clone的方法

   /**     * Copy constructor.     */    public Intent(Intent o) {        this.mAction = o.mAction;        this.mData = o.mData;        this.mType = o.mType;        this.mPackage = o.mPackage;        this.mComponent = o.mComponent;        this.mFlags = o.mFlags;        this.mContentUserHint = o.mContentUserHint;        if (o.mCategories != null) {            this.mCategories = new ArraySet<String>(o.mCategories);        }        if (o.mExtras != null) {            this.mExtras = new Bundle(o.mExtras);        }        if (o.mSourceBounds != null) {            this.mSourceBounds = new Rect(o.mSourceBounds);        }        if (o.mSelector != null) {            this.mSelector = new Intent(o.mSelector);        }        if (o.mClipData != null) {            this.mClipData = new ClipData(o.mClipData);        }    }    @Override    public Object clone() {        return new Intent(this);    }

 

Android 設計模式之原型模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.