美文网首页
装饰模式

装饰模式

作者: juconcurrent | 来源:发表于2018-10-26 23:32 被阅读5次

概念

所谓装饰模式,就是在不改变有功能的情况下,对功能进行额外的包装,以扩展其功能。通过创建一个包装对象来包裹真实对象。

示例

public interface If {

    /**
     * if判断条件
     *
     * @return true:继续执行,false:停止执行
     */
    boolean meet();
}
public interface Bundle {

    void call(Context context);
}
public class IfBundle implements Bundle {

    private If anIf;
    private Bundle bundle;

    public IfBundle(If anIf, Bundle bundle) {
        this.anIf = anIf;
        this.bundle = bundle;
    }

    @Override public void call(Context context) {
        if (isNull(anIf) || anIf.meet()) {
            bundle.call(context);
        }
    }
}
public class ForBundle implements Bundle {

    private int number;
    private Bundle bundle;

    public ForBundle(int number, Bundle bundle) {
        this.number = number;
        this.bundle = bundle;
    }

    @Override public void call(Context context) {
        if (number > 0) {
            for (int i = 0; i < number; i++) {
                bundle.call(context);
            }
        }
    }
}
public class LoopBundle implements Bundle {

    private If anIf;
    private Bundle bundle;

    public LoopBundle(If anIf, Bundle bundle) {
        this.anIf = anIf;
        this.bundle = bundle;
    }

    @Override public void call(Context context) {
        while (isNull(anIf) || anIf.meet()) {
            bundle.call(context);
        }
    }
}

相关文章

网友评论

      本文标题:装饰模式

      本文链接:https://www.haomeiwen.com/subject/yurrtqtx.html