Introduction to the application and advantages of the Android source Learning factory Method _android

Source: Internet
Author: User
Factory method Pattern Definition
Define an interface for creating a object, but let subclasses decide class to which. Factory method lets a class defer instantiation to subclasses.
Defines an interface for creating objects, letting subclasses decide which class to instantiate. The factory method defers the instantiation of a class to its subclasses.

common mode Structure of factory method


As shown in the figure above (intercepted from the head Patterns), it consists of four main parts:
Abstract Product class product is responsible for defining the generality of the product, and for the definition of things abstract; creator is the abstract creation class, the abstract factory, how to create the product class is accomplished by the concrete implementation factory Concretecreator. In the "head of the design Patterns" on the Factory mode of the details of the description, the original text is as follows:
As in the official definition, you'll often hear developers say this Factory method lets subclasses decide class to instantiate. They say "Decides" not because the pattern allows subclasses themselves to decide at runtime, but because the creator Clas S is written without knowledge of the actual products that'll be created, which are decided purely by the choice of the S Ubclass is used.

What are the advantages of the factory method model?
Good encapsulation, the structure of the code is clear. An object creates a conditional constraint, and if a caller needs a specific product object, it is OK to know the class name of the product, without knowing the process of creating the object and reducing the coupling between the modules.

Scalability is good. In the case of adding a product class, you can complete it by modifying the specific factory class or extending a factory class as appropriate.
Shielding Product class. How the implementation of the product class changes, the caller does not need to care, it only needs to care about the product interface, as long as the interface remains unchanged, the system's upper modules do not have to change. Since the instantiation of the product class is the responsibility of the factory class, it is up to the factory class to determine which product the product object is generated from. Furthermore, the factory method model is a typical loosely coupled structure. The high-level module only needs to know the product abstract class, other realization class All does not need the relation, conforms to the Dimitri rule, the dependence inverted principle, the Richter substitution principle and so on.

In the Android source code, listactivity inherits from the activity, takes the activity as the factory method, produces the activity with the ListView characteristic, the description of listactivity is as follows:
An activity so displays a list of items by binding to a data source such as an array or Cursor, and exposes event handle RS when the user selects an item.
Listactivity hosts a ListView object can bound to different data sources, typically either an array or a Cursor ho lding query results. Binding, screen layout, and row layout are discussed in the following.

Screen Layout
Listactivity has a default layout that consists of "a single", Full-screen list in the center of the "screen." However, if you are desire, you can customize the screens layout by setting your own view layout and Setcontentview () in Oncre Ate (). To does this, your own view must contain a ListView object with the id "@android: Id/list" (or listif it's in code)

there is a function in the activity class
Copy Code code as follows:

/**
* This is called after {@link #onStart} the
* Being re-initialized from a previously saved state, given
* <VAR>SAVEDINSTANCESTATE</VAR>. Most implementations'll simply use {@link #onCreate}
* To restore their state, but it are sometimes convenient to does it here
* After all of the initialization has been do or to allow subclasses to
* Decide whether to use your default implementation. The default
* Implementation of this method performs a restore of the any view state that
* had previously been frozen by {@link #onSaveInstanceState}.
*
* <p>this method is called between {@link #onStart} and
* {@link #onPostCreate}.
*
* @param savedinstancestate The data most recently supplied in {@link #onSaveInstanceState}.
*
* @see #onCreate
* @see #onPostCreate
* @see #onResume
* @see #onSaveInstanceState
*/
protected void Onrestoreinstancestate (Bundle savedinstancestate) {
if (Mwindow!= null) {
Bundle WindowState = Savedinstancestate.getbundle (Window_hierarchy_tag);
if (WindowState!= null) {
Mwindow.restorehierarchystate (WindowState);
}
}
}

In the note, "but it is sometimes convenient todo it here," the initialization has been done or to allow subclasses to Decide whether to use your default implementation. ", English is not very good, but the general meaning is that the activity subclasses can overload this function to determine whether the default implementation is used.

looking at the subclass Listactivity
Copy Code code as follows:

public class Listactivity extends activity {
/**
* This field should be made private and so it's hidden from the SDK.
* {@hide}
*/
protected ListAdapter Madapter;
/**
* This field should be made private and so it's hidden from the SDK.
* {@hide}
*/
protected ListView mlist;
Private Handler Mhandler = new Handler ();
Private Boolean mfinishedstart = false;
Private Runnable Mrequestfocus = new Runnable () {
public void Run () {
Mlist.focusableviewavailable (mlist);
}
};
/**
* This method would be called when a item in the ' list is selected.
* Subclasses should override. Subclasses can call
* Getlistview (). Getitematposition (position) if they need to access the
* Data associated with the selected item.
*
* @param l The ListView where the click happened
* @param v The view that is clicked within the ListView
* @param position the position of the view in the list
* @param ID The row ID of the item that is clicked
*/
protected void Onlistitemclick (ListView l, View v, int position, long ID) {
}
/**
* Ensures the list view has been created before activity restores all
* The view states.
*
* @see Activity#onrestoreinstancestate (Bundle)
*/
@Override
protected void Onrestoreinstancestate (Bundle state) {
Ensurelist ();
Super.onrestoreinstancestate (state);
}
/**
* @see Activity#ondestroy ()
*/
@Override
protected void OnDestroy () {
Mhandler.removecallbacks (Mrequestfocus);
Super.ondestroy ();
}
/**
* Updates the "screen state" when the
* Content changes.
*
* @see activity#oncontentchanged ()
*/
@Override
public void oncontentchanged () {
Super.oncontentchanged ();
View Emptyview = Findviewbyid (com.android.internal.r.id.empty);
Mlist = (ListView) Findviewbyid (com.android.internal.r.id.list);
if (mlist = = null) {
throw New RuntimeException (
"Your content must have a ListView whose id attribute is" +
"' Android. R.id.list ' ");
}
if (Emptyview!= null) {
Mlist.setemptyview (Emptyview);
}
Mlist.setonitemclicklistener (Monclicklistener);
if (Mfinishedstart) {
Setlistadapter (Madapter);
}
Mhandler.post (Mrequestfocus);
Mfinishedstart = true;
}
/**
* Provide the cursor for the list view.
*/
public void Setlistadapter (ListAdapter adapter) {
Synchronized (this) {
Ensurelist ();
Madapter = adapter;
Mlist.setadapter (adapter);
}
}
/**
* Set the currently selected list item to the specified
* Position with the adapter ' s data
*
* @param position
*/
public void setselection (int position) {
Mlist.setselection (position);
}
/**
* Get the position of the currently selected list item.
*/
public int getselecteditemposition () {
return Mlist.getselecteditemposition ();
}
/**
* Get the cursor row ID of the currently selected list item.
*/
Public long Getselecteditemid () {
return Mlist.getselecteditemid ();
}
/**
* Get the activity ' s List View widget.
*/
Public ListView Getlistview () {
Ensurelist ();
return mlist;
}
/**
* Get the ListAdapter associated with this activity ' s ListView.
*/
Public ListAdapter Getlistadapter () {
return madapter;
}
private void Ensurelist () {
if (mlist!= null) {
Return
}
Setcontentview (com.android.internal.r.layout.list_content_simple);
}
Private Adapterview.onitemclicklistener Monclicklistener = new Adapterview.onitemclicklistener () {
public void Onitemclick (adapterview<?> parent, View v, int position, long ID)
{
Onlistitemclick ((ListView) parent, V, position, id);
}
};
}

The function onrestoreinstancestate (Bundle state) is overwritten and the default Setcontentview is set in view (Com.android.internal.r.layout.list_ Content_simple);
Copy Code code as follows:

/**
* Ensures the list view has been created before activity restores all
* The view states.
*
* @see Activity#onrestoreinstancestate (Bundle)
*/
@Override
protected void Onrestoreinstancestate (Bundle state) {
Ensurelist ();
Super.onrestoreinstancestate (state);
}
。。。
private void Ensurelist () {
if (mlist!= null) {
Return
}
Setcontentview (com.android.internal.r.layout.list_content_simple);
}

the Setcontentview () function in activity
Copy Code code as follows:

/**
* Set the activity content from a layout resource. The resource would be
* inflated, adding all top-level views to the activity.
*
* @param layoutresid Resource ID to be inflated.
*
* @see #setContentView (Android.view.View)
* @see #setContentView (Android.view.View, Android.view.ViewGroup.LayoutParams)
*/
public void Setcontentview (int layoutresid) {
GetWindow (). Setcontentview (LAYOUTRESID);
Initactionbar ();
}
/**
* Set the activity content to an explicit view. This view is placed
* Directly into the activity ' s view hierarchy. It can itself be a complex
* View hierarchy. When calling this method, the layout parameters of the
* Specified view are ignored. Both the width and the height of the view are
* Set by default to {@link viewgroup.layoutparams#match_parent}. To use
* Your own layout parameters, invoke
* {@link #setContentView (Android.view.View, Android.view.ViewGroup.LayoutParams)}
* instead.
*
* @param view the desired content to display.
*
* @see #setContentView (int)
* @see #setContentView (Android.view.View, Android.view.ViewGroup.LayoutParams)
*/
public void Setcontentview (view view) {
GetWindow (). Setcontentview (view);
Initactionbar ();
}
/**
* Set the activity content to an explicit view. This view is placed
* Directly into the activity ' s view hierarchy. It can itself be a complex
* View hierarchy.
*
* @param view the desired content to display.
* @param params Layout parameters for the view.
*
* @see #setContentView (Android.view.View)
* @see #setContentView (int)
*/
public void Setcontentview (view view, Viewgroup.layoutparams params) {
GetWindow (). Setcontentview (view, params);
Initactionbar ();
}


Summary: Activity as a "factory method", the specific view shows what is implemented by default settings or by subclasses; Listactivity as a concrete implementation, it determines that the ListView is displayed in the view; The view here is the default display in the activity, which is " Product ", and ListView is" concreteproduct ", determined by listactivity to display.

In addition to listactivity, there are expandablelistactivity also activity for the factory class, create their own display effect.
My ability and time limited (lack of "mode use" content, will be added later), write very rough, waiting for everyone's criticism, thank you ~ ~ ~
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.