针对View和ViewGroup的实际情况,我们选择安全式的组合模式(在组合对象中添加add,remove,getChild方法),添加少许的注释,我们把上图修改为:
3.代码
View类的实现:
public class View{ //... ... //省略了无关的方法 } ViewGroup的实现:public abstract class ViewGroup extends View{ /** * Adds a child view. */ public void addView(View child) { //... } public void removeView(View view) { //... } /** * Returns the view at the specified position in the group. */ public View getChildAt(int index) { try { return mChildren[index]; } catch (IndexOutOfBoundsException ex) { return null; } } //other methods }4.效果