android 之 activity 和 controller 架构设计

本文深入探讨了在Android开发中Activity与Controller的架构设计,解析它们在应用程序中的角色与区别。通过实例分析,阐述如何合理选择与结合使用,以实现高效、可维护的代码结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public abstract class ActivityBase extends Activity {

    public static final String TAG = "ActivityBase";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    protected void onDestroy() {
        if (_activityControllers != null) {
            for (int i = 0; i < _activityControllers.size(); i++) {
                ControllerBase child = _activityControllers.get(i);
                child.internal_gc();
            }
            _activityControllers = null;
        }

        unregisterEventBus();
        super.onDestroy();
    }
    
    protected void registerEventBus() {
        isRegisterEventBus = true;
        EventBus.getDefault().register(this);
    }

    protected void unregisterEventBus() {
        if (isRegisterEventBus){
            EventBus.getDefault().unregister(this);
            isRegisterEventBus = false;
        }
    }

    protected void addActivityController(ControllerBase child) {
        if (_activityControllers == null) {
            _activityControllers = new ArrayList<>();
        }
        _activityControllers.add(child);
    }
    
    protected List<ControllerBase> _activityControllers;
    protected Boolean isRegisterEventBus = false;
}


public abstract class ControllerBase {

    //子 Controller 由 父 Controller 管理
    //子 Controller 在父 Controller 实例化
    public ControllerBase(ControllerBase parent) {
        parent.addChild(this);
    }

    //附着 activity
    public ControllerBase(ActivityBase activity) {
        activity.addActivityController(this);
    }

    //do not directly call it, it will call by internal_gc() when activity destroyed
    abstract protected void gc();

    //call by ActivityBase when it destroyed
    protected void internal_gc() {
        if (_childController != null) {
            for (int i = 0; i < _childController.size(); i++) {
                ControllerBase child = _childController.get(i);
                child.internal_gc();
            }
            _childController = null;
        }

        gc();
    }

    private void addChild(ControllerBase child) {
        if (_childController == null) {
            _childController = new ArrayList<>();
        }
        _childController.add(child);
    }

    List<ControllerBase> _childController;
}



























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值