工厂方法模式定义:
define an interface for creating an object, but let subclasses decide which class to instantiate. factory method lets a class defer instantiation to subclasses.
定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
常用的工厂方法模式结构:
如上图所示(截取自《head first design patterns》一书),主要包括四个部分:
抽象产品类product负责定义产品的共性,实现对事物抽象的定义;creator是抽象创建类,也就是抽象工厂,具体如何创建产品类是由具体的实现工厂concretecreator完成的。其中在《head first design patterns》对工厂方法模式做了细节的说明,原文如下:
as in the official definition, you'll often hear developers say that the factory method lets subclasses decide which class to instantiate. they say “decides” not because the pattern allows subclasses themselves to decide at runtime, but because the creator class is written without knowledge of the actual products that will be created, which is decided purely by the choice of the subclass that is used.
工厂方法模式有什么优势呢:
良好的封装性,代码结构清楚。一个对象创建具有条件约束的,如果一个调用者需要一个具体的产品对象,只要知道这个产品的类名就可以了,不用知道创建对象的过程,降低模块间的耦合。
可扩展性好。在增加产品类的情况下,只要适当的修改具体的工厂类或扩展一个工厂类,就可以完成。
屏蔽产品类。产品类的实现如何变化,调用者都不需要关心,它只需要关心产品的接口,只要接口保持不变,系统中的上层模块就不用改变。因为产品类的实例化工作是由工厂类负责的,一个产品对象具体由哪一个产品生成是由工厂类决定的。此外工厂方法模式是典型的松耦合结构。高层模块只需要知道产品的抽象类,其他的实现类都不用关系,符合迪米特法则、依赖倒置原则、里氏替换原则等。
在android源码中,listactivity继承自activity,将activity作为工厂方法,生成具有listview特点的activity,对listactivity的说明如下:
an activity that displays a list of items by binding to a data source such as an array or cursor, and exposes event handlers when the user selects an item.
listactivity hosts a listview object that can be bound to different data sources, typically either an array or a cursor holding query results. binding, screen layout, and row layout are discussed in the following sections.
screen layout
listactivity has a default layout that consists of a single, full-screen list in the center of the screen. however, if you desire, you can customize the screen layout by setting your own view layout with setcontentview() in oncreate(). to do this, your own view must contain a listview object with the id "@android:id/list" (or listif it's in code)
在activity类中有这么一个函数:
复制代码 代码如下:
/**
* this method is called after {@link #onstart} when the activity is
* being re-initialized from a previously saved state, given here in
* <var>savedinstancestate</var>. most implementations will simply use {@link #oncreate}
* to restore their state, but it is sometimes convenient to do it here
* after all of the initialization has been done or to allow subclasses to
* decide whether to use your default implementation. the default
* implementation of this method performs a restore of 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);
}
}
}
在注释中“but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation.”,英语不太好,但大致的意思是activity子类可以重载这个函数来决定是否使用默认的实现。
在看子类listactivity:
复制代码 代码如下:
public class listactivity extends activity {
/**
* this field should be made private, so it is hidden from the sdk.
* {@hide}
*/
protected listadapter madapter;
/**
* this field should be made private, so it is 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 will be called when an 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 was clicked within the listview
* @param position the position of the view in the list
* @param id the row id of the item that was clicked
*/
protected void onlistitemclick(listview l, view v, int position, long id) {
}
/**
* ensures the list view has been created before activity restores all
* of 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 (current list and other views) 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);
}
};
}
其中复写了函数onrestoreinstancestate(bundle state),并在view中设置了默认的setcontentview(com.android.internal.r.layout.list_content_simple);
复制代码 代码如下:
/**
* ensures the list view has been created before activity restores all
* of 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);
}
activity中的setcontentview()函数:
复制代码 代码如下:
/**
* set the activity content from a layout resource. the resource will 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();
}
总结:activity作为“工厂方法”,具体view中显示什么由默认设置或者由子类来实现;listactivity作为具体实现,它决定在view中显示的是listview;这里的view是activity中的默认显示,即为“product”,而listview是“concreteproduct”,由listactivity来决定显示。
除了listactivity以外,还有expandablelistactivity也是以activity为工厂类,创建自己的显示效果。
本人能力和时间有限(缺少“模式使用”内容,以后会添加),写的很粗糙,恭候大家的批评指正,谢谢~~~