lifecycle简单理解
在线看源码地址:
https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:lifecycle/
如需git clone,可使用下面两个地址
https://android.googlesource.com/platform/frameworks/support/
https://github.com/androidx/androidx
如需将 androidx.lifecycle
导入 Android 项目,请参阅 Lifecycle 版本说明中关于声明依赖项的说明。
1.lifecycle是什么
是androidx下的一个软件包,里面有livedata,viewmodel等。
https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:lifecycle/
这个package下有一个类,叫Lifecycle.java
2.LifeCycle
Lifecycle 是一个类,用于存储有关组件(如 Activity 或 Fragment)的生命周期状态的信息,并允许其他对象观察此状态。
https://developer.android.com/topic/libraries/architecture/lifecycle?hl=zh-cn
androidx.lifecycle 软件包 提供了可用于构建生命周期感知型组件的类和接口- 这些组件可以根据 Activity 或 Fragment 的当前生命周期状态自动调整其行为。
在 Android 框架中定义的大多数应用组件都存在生命周期。生命周期由操作系统或进程中运行的框架代码管理。它们是 Android 工作原理的核心,应用必须遵循它们。如果不这样做,可能会引发内存泄漏甚至应用崩溃。
简单来说,activity和fragment 这种Android框架中的组件是有生命周期的,但是自定义的一些类,是没有生命周期的,通过使用lifecycle 软件包,可以使自定义的类,具备感知生命周期的功能。
Lifecycle 是个抽象类,下面简单列出几个关键点。
public abstract class Lifecycle {
/**
* Adds a LifecycleObserver that will be notified when the LifecycleOwner changes
* state.
* <p>
* The given observer will be brought to the current state of the LifecycleOwner.
* For example, if the LifecycleOwner is in {@link State#STARTED} state, the given observer
* will receive {@link Event#ON_CREATE}, {@link Event#ON_START} events.
*
* @param observer The observer to notify.
*/
//注释简单翻译
// 添加一个 LifecycleObserver,当 LifecycleOwner 发生变化时会收到通知状态
//例如,如果 LifecycleOwner 处于 {@link State#STARTED} 状态,则给定的观察者将接收 {@link Event#ON_CREATE}、{@link Event#ON_START} 事件
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
}
@SuppressWarnings("WeakerAccess")
public enum Event {
/**
* Constant for onCreate event of the {@link LifecycleOwner}.
*/
ON_CREATE,
/**
* Constant for onStart event of the {@link LifecycleOwner}.
*/
ON_START,
...
}
/**
* Lifecycle states. You can consider the states as the nodes in a graph and
* {@link Event}s as the edges between these nodes.
*/
@SuppressWarnings("WeakerAccess")
public enum State {
/**
* Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onStart() onStart} call;
* <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
* </ul>
*/
STARTED,
...
}
}
从这里命名这里可以看出,使用的是观察者模式。也就是有观察者和被观察者。LifecycleOwner 是被观察者,LifecycleObserver是观察者。
可以想象这样一个场景:人要过马路看红绿灯,红绿灯就是被观察者,人就是观察者,红绿灯状态会发生变化,人需要根据变化做出改变。
添加一个 LifecycleObserver,当 LifecycleOwner 发生变化时会收到通知状态。例如,如果 LifecycleOwner 处于 {@link State#STARTED} 状态,则给定的观察者将接收 {@link Event#ON_CREATE}、{@link Event#ON_START} 事件。
LifeCycle的简单使用:
添加依赖
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation "androidx.lifecycle:lifecycle-common:2.2.0"
implementation "androidx.lifecycle:lifecycle-common-java8:2.2.0"
implementation "androidx.lifecycle:lifecycle-runtime:2.2.0"
lifecycle调用addObserver() 传入Observer 。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d("MainActivity","inner onCreate")
lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
Log.d("Observer","inner onCreate")
}
override fun onResume(owner: LifecycleOwner) {
Log.d("Observer","inner onResume")
}
override fun onDestroy(owner: LifecycleOwner) {
Log.d("Observer","inner onDestroy")
}
})
}
override fun onResume() {
super.onResume()
Log.d("MainActivity","inner onResume")
}
override fun onDestroy() {
super.onDestroy()
Log.d("MainActivity","inner onDestroy")
}
}
运行后结果如下所示。随着activity生命周期发生变化,会执行DefaultLifecycleObserver 中重写的函数。
image.png
这里的lifecycle实际是一个mLifecycleRegistry。因为ComponentActivity 实现了LifecycleOwner接口,所以要重写getLifecycle()。
https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:lifecycle/lifecycle-common/src/main/java/androidx/lifecycle/LifecycleOwner.java
@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
MainActivity继承自ComponentActivity ,因此能调用getLifecycle(),那么问题来了。
Android 是怎么做到当给传入一个观察者之后,能执行onCreate等生命周期同名函数的?
下面以ComponentActivity这个类为入口去分析。
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
ContextAware,
LifecycleOwner,
...{
...
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
...
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
...
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
// Restore the Saved State first so that it is available to
// OnContextAvailableListener instances
mSavedStateRegistryController.performRestore(savedInstanceState);
mContextAwareHelper.dispatchOnContextAvailable(this);
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
}
执行了private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
/**
* Creates a new LifecycleRegistry for the given provider.
* <p>
* You should usually create this inside your LifecycleOwner class's constructor and hold
* onto the same instance.
*
* @param provider The owner LifecycleOwner
*/
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
this(provider, true);
}
private LifecycleRegistry(@NonNull LifecycleOwner provider, boolean enforceMainThread) {
// 传入 ComponentActivity这个LifecycleOwner,并使用弱引用
mLifecycleOwner = new WeakReference<>(provider);
//更新 androidx.lifecycle.Lifecycle.State 状态
mState = INITIALIZED;
mEnforceMainThread = enforceMainThread;
}
//后面再分析这个函数
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
enforceMainThreadIfNeeded("addObserver");
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// observer转换成ObserverWithState,存储LifecycleEventObserver和State(androidx.lifecycle.Lifecycle.State)
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
...
}
在ComponentActivity的onCreate方法中,把生命周期的处理交给ReportFragment,代码如下:
https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:lifecycle/lifecycle-runtime/src/main/java/androidx/lifecycle/ReportFragment.java
public static void injectIfNeededIn(Activity activity) {
//API29及其以上,监听activity生命周期的逻辑
if (Build.VERSION.SDK_INT >= 29) {
// On API 29+, we can register for the correct Lifecycle callbacks directly
LifecycleCallbacks.registerIn(activity);
}
//API29以下,通过在activity添加一个空UI的Fragment,然后监听Fragment的生命周期就是Activity的生命周期
// Prior to API 29 and to maintain compatibility with older versions of
// ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
// need to support activities that don't extend from FragmentActivity from support lib),
// use a framework fragment to get the correct timing of Lifecycle events
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
// Hopefully, we are the first to make a transaction.
manager.executePendingTransactions();
}
}
@RequiresApi(29)
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
static void registerIn(Activity activity) {
//通过activity提供的接口,监听生命周期,是在API29才加入的接口
activity.registerActivityLifecycleCallbacks(new ReportFragment.LifecycleCallbacks());
}
@Override
public void onActivityPostCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
//监听到相应的生命周期,分发事件
dispatch(activity, Lifecycle.Event.ON_CREATE);
}
//......其他事件
@Override
public void onActivityPrePaused(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_PAUSE);
}
}
走到Activity.java的registerActivityLifecycleCallbacks中。
https://cs.android.com/android/platform/superproject/+/master:frameworks/base/core/java/android/app/Activity.java
private final ArrayList<Application.ActivityLifecycleCallbacks> mActivityLifecycleCallbacks =
new ArrayList<Application.ActivityLifecycleCallbacks>();
public void registerActivityLifecycleCallbacks(
@NonNull Application.ActivityLifecycleCallbacks callback) {
synchronized (mActivityLifecycleCallbacks) {
mActivityLifecycleCallbacks.add(callback);
}
}
这个callback是哪里调用的呢?
直接点击这个,在线查找。翻到activity中的部分可以看到如下所示。
image.png
这里点进dispatchActivityPreStarted中去看下。
private void dispatchActivityPreStarted() {
getApplication().dispatchActivityPreStarted(this);
Object[] callbacks = collectActivityLifecycleCallbacks();
if (callbacks != null) {
for (int i = 0; i < callbacks.length; i++) {
((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreStarted(this);
}
}
}
如果对activity启动流程有一定的了解的话,就知道启动过程中会调用activity.performStart()。
而performStart中调用了dispatchActivityPreStarted。
final void performStart(String reason) {
dispatchActivityPreStarted();
...
}
因此,activity启动后,调用了ReportFragment中重写的 onActivityCreated,onActivityPostCreated,onActivityPostStarted等回调函数。
调用onActivityPostCreated,从而执行 dispatch(activity, Lifecycle.Event.ON_CREATE);
。
最终会走到handleLifecycleEvent。
https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:lifecycle/lifecycle-runtime/src/main/java/androidx/lifecycle/ReportFragment.java
@SuppressWarnings("deprecation")
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
getLifecycle()返回的是LifecycleRegistry,然后走到handleLifecycleEvent。
简单小结:
通过在ReportFragment中调用activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
,将LifecycleCallbacks传入Activity,从而使得activty启动的时候,调用onActivityPostCreated,然后走到observer.dispatchEvent(lifecycleOwner, event);
,最终走到handleLifecycleEvent(LifecycleRegistry中)
。
/**
* Sets the current state and notifies the observers.
* <p>
* Note that if the {@code currentState} is the same state as the last call to this method,
* calling this method has no effect.
*
* @param event The event that was received
*/
// 设置当前状态并通知观察者
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
moveToState(event.getTargetState());
}
private void moveToState(State next) {
...
mHandlingEvent = true;
sync();
mHandlingEvent = false;
...
}
private void sync() {
...
while (!isSynced()) {
mNewEventOccurred = false;
// no need to check eldest for nullability, because isSynced does it for us.
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
...
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
...
}
private void backwardPass(LifecycleOwner lifecycleOwner) {
...
observer.dispatchEvent(lifecycleOwner, event);
...
}
private void forwardPass(LifecycleOwner lifecycleOwner) {
...
observer.dispatchEvent(lifecycleOwner, event);
...
}
observer.dispatchEvent(lifecycleOwner, event);
中的observer是哪里来的?
LifecycleRegistry.java这个类中的函数addObserver的时候传入的observer。
在调用addObserver传入LifecycleObserver添加观察者的时候 ,LifecycleObserver会被封装成
ObserverWithState放到mObserverMap中,需要用的时候再取出来。
addObserver这里也会走到dispatchEvent(LifecycleOwner owner, Event event)
中。
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
//确保在主线程运行
//当mEnforceMainThread为true时,必须是在主线程调用,否则抛出异常
enforceMainThreadIfNeeded("addObserver");
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// observer转换成ObserverWithState,存储LifecycleEventObserver和State
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//以observer为key,将observer和statefulObserver存到mObserverMap中
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
...
//计算目标状态,目的是从初始化状态遍历到当前实际状态,然后把每一个状态的事件分发
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
final Event event = Event.upFrom(statefulObserver.mState);
if (event == null) {
throw new IllegalStateException("no event up from " + statefulObserver.mState);
}
//分发事件
statefulObserver.dispatchEvent(lifecycleOwner, event);
...
}
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
...
mLifecycleObserver.onStateChanged(owner, event);
...
}
}
dispatchEvent这里重点关注下mLifecycleObserver.onStateChanged(owner, event);
mLifecycleObserver是通过Lifecycling.lifecycleEventObserver(observer)转换而来的一个LifecycleEventObserver 对象。这个observer就是前面MainActivity中addObserver传入的observer。LifecycleEventObserver,生命周期事件观察者,一个接口。
public interface LifecycleEventObserver extends LifecycleObserver {
/**
* Called when a state transition event happens.
*
* @param source The source of the event
* @param event The event
*/
void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
哪里重写了这个回调并传入?
答案在Lifecycling.lifecycleEventObserver(observer)里。
@NonNull
@SuppressWarnings("deprecation")
static LifecycleEventObserver lifecycleEventObserver(Object object) {
boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
if (isLifecycleEventObserver && isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
(LifecycleEventObserver) object);
}
if (isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
}
if (isLifecycleEventObserver) {
return (LifecycleEventObserver) object;
}
//如果观察者是通过实现LifecycleObserver,并用注解 @OnLifecycleEvent修饰方法这样的方式实现的,
//就走下面的逻辑,会用反射实现
//因为会用到反射,所以会有性能问题,不推荐使用
final Class<?> klass = object.getClass();
int type = getObserverConstructorType(klass);
if (type == GENERATED_CALLBACK) {
List<Constructor<? extends GeneratedAdapter>> constructors =
sClassToAdapters.get(klass);
if (constructors.size() == 1) {
GeneratedAdapter generatedAdapter = createGeneratedAdapter(
constructors.get(0), object);
return new SingleGeneratedAdapterObserver(generatedAdapter);
}
GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
for (int i = 0; i < constructors.size(); i++) {
adapters[i] = createGeneratedAdapter(constructors.get(i), object);
}
return new CompositeGeneratedAdaptersObserver(adapters);
}
return new ReflectiveGenericLifecycleObserver(object);
}
这里先判断observer的类型,然后转换成FullLifecycleObserverAdapter。这里面重写了onStateChanged。
class FullLifecycleObserverAdapter implements LifecycleEventObserver {
private final FullLifecycleObserver mFullLifecycleObserver;
private final LifecycleEventObserver mLifecycleEventObserver;
FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,
LifecycleEventObserver lifecycleEventObserver) {
mFullLifecycleObserver = fullLifecycleObserver;
mLifecycleEventObserver = lifecycleEventObserver;
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
switch (event) {
case ON_CREATE:
mFullLifecycleObserver.onCreate(source);
break;
case ON_START:
mFullLifecycleObserver.onStart(source);
break;
case ON_RESUME:
mFullLifecycleObserver.onResume(source);
break;
}
....
}
}
dispatchEvent的mLifecycleObserver.onStateChanged ,实际调用的是FullLifecycleObserverAdapter 中的onStateChanged。
//LifecycleRegistry.java
void dispatchEvent(LifecycleOwner owner, Event event) {
...
mLifecycleObserver.onStateChanged(owner, event);
...
}
当有event事件分发下来,例如分发ON_CREATE, 那么会走到mFullLifecycleObserver.onCreate(source);
https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:lifecycle/lifecycle-common/src/main/java/androidx/lifecycle/FullLifecycleObserver.java
interface FullLifecycleObserver extends LifecycleObserver {
void onCreate(LifecycleOwner owner);
void onStart(LifecycleOwner owner);
void onResume(LifecycleOwner owner);
void onPause(LifecycleOwner owner);
void onStop(LifecycleOwner owner);
void onDestroy(LifecycleOwner owner);
}
FullLifecycleObserver 只是一个接口,没有真正的函数实现,实际函数实现在哪里?
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d("MainActivity","inner onCreate")
lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
Log.d("Observer","inner onCreate")
}
override fun onResume(owner: LifecycleOwner) {
Log.d("Observer","inner onResume")
}
override fun onDestroy(owner: LifecycleOwner) {
Log.d("Observer","inner onDestroy")
}
})
}
override fun onResume() {
super.onResume()
Log.d("MainActivity","inner onResume")
}
override fun onDestroy() {
super.onDestroy()
Log.d("MainActivity","inner onDestroy")
}
}
前面MainActivity 中使用了匿名内部类DefaultLifecycleObserver ,DefaultLifecycleObserver 继承FullLifecycleObserver 。
public interface DefaultLifecycleObserver extends FullLifecycleObserver {
@Override
default void onCreate(@NonNull LifecycleOwner owner) {
}
...
}
所以 mFullLifecycleObserver.onCreate(source);的具体实现是在新建工程的自定义类MainActivity中 ,也就是
// MainActivity
override fun onCreate(owner: LifecycleOwner) {
Log.d("Observer","inner onCreate")
}
使用lifecycler的情况下,activity启动简单流程调用如下:
performCreate
-> dispatchActivityPostCreated()
-> onActivityPostCreated
-> dispatch(activity, Lifecycle.Event.ON_CREATE)
-> handleLifecycleEvent(event)
-> dispatchEvent(lifecycleOwner, event)
-> mLifecycleObserver.onStateChanged(owner, event)
-> mFullLifecycleObserver.onCreate(source)
-> DefaultLifecycleObserver中自己重写的override fun onCreate(owner: LifecycleOwner)
上面这部分就是当生命周期发生变化时的事件分发流程。接下来,着重来看下Lifecycle这个类中的State 。
https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:lifecycle/lifecycle-common/src/main/java/androidx/lifecycle/Lifecycle.java
@SuppressWarnings("WeakerAccess")
public enum State {
/**
* Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
* any more events. For instance, for an {@link android.app.Activity}, this state is reached
* <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
*/
DESTROYED,
/**
* Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
* the state when it is constructed but has not received
* {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
*/
INITIALIZED,
/**
* Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
* <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
* </ul>
*/
CREATED,
/**
* Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onStart() onStart} call;
* <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
* </ul>
*/
STARTED,
/**
* Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached after {@link android.app.Activity#onResume() onResume} is called.
*/
RESUMED;
/**
* Compares if this State is greater or equal to the given {@code state}.
*
* @param state State to compare with
* @return true if this State is greater or equal to the given {@code state}
*/
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
在此之前,先了解下状态模式的架构和使用枚举实现状态机。了解状态模式的引入是为了解决什么问题,以及状态模式的架构,以及状态机之后,才能更清晰地理解Lifecycle的设计。
https://blog.csdn.net/lovelion/article/details/8522982“人有悲欢离合,月有阴晴圆缺”,包括人在内,很多事物都具有多种状态,而且在不同状态下会具有不同的行为,这些状态在特定条件下还将发生相互转换。就像水,它可以凝固成冰,也可以受热蒸发后变成水蒸汽,水可以流动,冰可以雕刻,蒸汽可以扩散。我们可以用UML状态图来描述H2O的三种状态,
在软件系统中,有些对象也像水一样具有多种状态,这些状态在某些情况下能够相互转换,而且对象在不同的状态下也将具有不同的行为。
不使用状态模式去定义一个账户类,并执行存取款操作的话,代码如下所示。
class Account {
private String state; //状态
private int balance; //余额
......
//存款操作
public void deposit() {
//存款
stateCheck();
}
//取款操作
public void withdraw() {
if (state.equalsIgnoreCase("NormalState") || state.equalsIgnoreCase("OverdraftState ")) {
//取款
stateCheck();
}
else {
//取款受限
}
}
//计算利息操作
public void computeInterest() {
if(state.equalsIgnoreCase("OverdraftState") || state.equalsIgnoreCase("RestrictedState ")) {
//计算利息
}
}
//状态检查和转换操作
public void stateCheck() {
if (balance >= 0) {
state = "NormalState";
}
else if (balance > -2000 && balance < 0) {
state = "OverdraftState";
}
else if (balance == -2000) {
state = "RestrictedState";
}
else if (balance < -2000) {
//操作受限
}
}
......
}
拥有一个较为复杂的stateCheck()方法,包含大量的if…else if…else…语句用于进行状态转换,不易于维护(if else写多了真的很难维护)。
使用状态模式可以解决这个问题。
状态模式定义如下:
状态模式(State Pattern):允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。其别名为状态对象(Objects for States),状态模式是一种对象行为型模式。
https://blog.csdn.net/lovelion/article/details/8523062
在状态模式中引入了抽象状态类和具体状态类
环境类维持一个对抽象状态类的引用,通过setState()方法可以向环境类注入不同的状态对象,再在环境类的业务方法中调用状态对象的方法,典型代码如下所示:
class Context {
private State state; //维持一个对抽象状态对象的引用
private int value; //其他属性值,该属性值的变化可能会导致对象状态发生变化
//设置状态对象
public void setState(State state) {
this.state = state;
}
public void request() {
//其他代码
state.handle(); //调用状态对象的业务方法
//其他代码
}
}
……
public void changeState() {
//判断属性值,根据属性值进行状态转换
if (value == 0) {
this.setState(new ConcreteStateA());
}
else if (value == 1) {
this.setState(new ConcreteStateB());
}
......
}
……
但是这种实现方式会会增加过多的状态对象依赖,有一种更好的实现方法,那就是使用枚举来实现状态机。
先来看看什么是状态机。
https://cloud.tencent.com/developer/article/1870480
状态机
一个状态机可能是有限状态机或者有限自动化,它是一个用来构造抽象机器的计算模型。
这些机器在特定时间节点只能有一种状态。一种状态到另外一种状态的变化叫做变更(transition)。
状态模式也是知名的GoF的32种设计模式之一。状态机是从数学中借鉴而来的概念。
用枚举实现状态机
通过枚举实现状态机的核心是,我们不需要明确设置状态,而是通过逻辑让状态流转到下一个状态
枚举实现状态机的优势
通过类或者接口方式实现状态机代码量非常大而且不容易维护。
而Java枚举则是一种简化的形式。
下面来看看Lifecycle 中 的 enum Event
和 enum State
。
https://segmentfault.com/a/1190000016443108
https://segmentfault.com/a/1190000016443108
State和Event,这也是贯穿整个Lifecycle的两个概念:状态和事件。
Lifecycle将Activity的生命周期函数对应成State,生命周期改变,会造成State改变,而State变化将触发Event事件,从而被LifecycleObser接收。
State:状态,是Lifecycle中对应Activity生命周期的一种状态标识,从图中可以看到,它有INITIALIZED、DESTROYED、CREATED、STARTED、RESUMED
这5中状态。
- INITIALIZED:对应Activity的onCreate之前的生命周期
- DESTROYED:对应Activity的onDestroy
- CREATED:对应Activity的onCreate到onStop之间的生命周期
- STARTED:对应Activity的onStart到onPause之间的生命周期
- RESUMED:对应Activity的onResume
Event:事件,当State发生变化时,Lifecycle会向已注册的LifecycleObserver发送事件,例如:当State从INITIALIZED变化到CREATED时,就会发出ON_CREATE事件。
以下面这个问题为引,加深下对状态机的理解。
https://segmentfault.com/a/1190000016443108
Event事件是如何分发到LifecycleObserver的?
LifecycleRegistry在收到handleLifecycleEvent()后,内部调用moveToState()方法,改变State值,每一次State值改变,都会调用LifecycleObserver.onStateChanged()方法将Event分发到LifecycleObserver。
最后,以一张流程图来结尾加深下印象(虽然部分类由于版本问题有差异,但是大致是这样的)。
http://liuwangshu.cn/application/jetpack/3-lifecycle-theory.html
参考链接:
官方文档:
Android Jetpack架构组件(三)带你了解Lifecycle(原理篇)
利用Java枚举实现简单的状态机
使用枚举实现状态机来优雅你的状态变更逻辑
处理对象的多种状态及其相互转换——状态模式(一)
处理对象的多种状态及其相互转换——状态模式(二)
https://developer.android.com/topic/libraries/architecture/lifecycle?hl=zh-cn
啃源码之--Lifecycle
一文搞懂Android JetPack组件原理之Lifecycle、LiveData、ViewModel与源码分析技巧
从源码看 Jetpack(1)- Lifecycle 源码详解
Android Jetpack架构组件(三)带你了解Lifecycle(原理篇)
Android-Lifecycle超能解析-生命周期的那些事儿