android常用设计模式之组合模式

一.定义

组合模式,将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。

 

二.角色

 1.Component(抽象结构) 是组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component子部件。

 2.Leaf(叶子结构) 在组合中表示叶子结点对象,叶子结点没有子结点。

 3.Composite (容器结构)定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和删除(remove)等。

 

三.实例说明

    组合模式使用最典型的例子就是文件系统了。

    在文件系统中,文件代表的就是叶子结点,文件夹代表的就是枝结点,文件和文件夹都可以有很多共性,如可以重命名、删除、添加等,但不同的是删除文件夹需要先删除文件夹下的文件。

1.抽象结构

/**
 * 组合模式-抽象结构类
 */
public abstract class FileComponent {
    public String rename(){
        throw new UnsupportedOperationException("不支持重命名操作");
    }

    public void add(){
        throw new UnsupportedOperationException("不支持添加操作");
    }

    public void delete(){
        throw new UnsupportedOperationException("不支持删除操作");
    }

}


2.容器结构-文件夹类

/**
 * 组合模式-容器结点-文件夹类
 */
public class Folder extends FileComponent{
    @Override
    public String rename() {
        return super.rename();
    }

    @Override
    public void add() {
        super.add();
    }

    @Override
    public void delete() {
        super.delete();
        System.out.print("删除时需先删除-文件夹下的子文件");
    }
}

 

3.叶子结构-文件类

/**
 * 组合模式-叶子结点-文件类
 */
public class File extends FileComponent{
    @Override
    public String rename() {
        return super.rename();
    }

    @Override
    public void add() {
        super.add();
    }

    @Override
    public void delete() {
        super.delete();
        System.out.print("直接删除");
    }
}

 

四.在android中的使用

 1.View-ViewGroup的使用:

  View做为叶子结点,ViewGroup做为容器结点即view的容器,ViewManager做为抽象结构类,定义了共有的接口:

 

 */
public interface ViewManager
{
    /**
     * Assign the passed LayoutParams to the passed View and add the view to the window.
     * <p>Throws {@link android.view.WindowManager.BadTokenException} for certain programming
     * errors, such as adding a second view to a window without removing the first view.
     * <p>Throws {@link android.view.WindowManager.InvalidDisplayException} if the window is on a
     * secondary {@link Display} and the specified display can't be found
     * (see {@link android.app.Presentation}).
     * @param view The view to be added to this window.
     * @param params The LayoutParams to assign to view.
     */
    public void addView(View view, ViewGroup.LayoutParams params);
    public void updateViewLayout(View view, ViewGroup.LayoutParams params);
    public void removeView(View view);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值