责任链模式

    xiaoxiao2021-03-25  95

    1.定义

    责任链模式是行为型设计模式之一,它使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止。

    2.实战演练

    用三个BroadcastReceiver来演示责任链事件处理 FirstReceiver (当limit==1000的时候获取msg打印并退出,否则添加一个新的msg给下一个Receicer)

    public class FirstReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int limit = intent.getIntExtra("limit", -1001); if(limit == 1000){ String msg = intent.getStringExtra("msg"); Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); abortBroadcast(); } else { Bundle b = new Bundle(); b.putString("new", "msg from FirstReceiver"); setResultExtras(b); } } }

    SecondReceiver(当limit==100的时候获取msg和上一个reveicer添加的msg打印并退出,否则添加一个新的msg给下一个Receicer)

    public class SecondReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int limit = intent.getIntExtra("limit", -1001); if(limit == 100){ String msg = intent.getStringExtra("msg"); Bundle b = getResultExtras(true); String str = b.getString("new"); Toast.makeText(context, msg + str, Toast.LENGTH_SHORT).show(); abortBroadcast(); } else { Bundle b = new Bundle(); b.putString("new", "msg from SecondReceiver"); setResultExtras(b); } } }

    ThirdReceiver(当limit==10的时候获取msg和上一个reveicer添加的msg打印并退出,否则添加一个新的msg给下一个Receicer)

    public class ThirdReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int limit = intent.getIntExtra("limit", -1001); if(limit == 10){ String msg = intent.getStringExtra("msg"); Bundle b = getResultExtras(true); String str = b.getString("new"); Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); abortBroadcast(); } else { Bundle b = new Bundle(); b.putString("new", "msg from ThirdReceiver"); setResultExtras(b); } } }

    测试用的MainActiviy(当然三个BroadcastReceiver也要设置优先级)

    Intent intent = new Intent(); intent.setAction("");//填在AndroidManifest.xml里面的action intent.putExtra("limit", 100); //只有SecondReceiver会来处理 intent.putExtra("msg", "msg from MainActivity"); sendOrderedBroadcast(intent, null);

    3.总结

    1.优点 可以对请求者和处理者的关系解耦,提高代码的灵活性。 2.缺点 每次都需要对链中请求处理者遍历,如果处理者太多那么遍历必定会影响性能,特别是在一些递归调用者中,要慎用。

    转载请注明原文地址: https://ju.6miu.com/read-25198.html

    最新回复(0)