装饰模式

装饰模式就是给一个对象增加一些新的功能,而且是动态的,要求装饰对象和被装饰对象实现同一个接口,装饰对象持有被装饰对象的实例,关系图如下:

(图片来自网络)
下面我们来看源码:
共同的接口:
public interface ModelMethodInterface {
    void doMethod();
}

被装饰者实现接口:
public class ModelObject implements ModelMethodInterface {

    @Override
    public void doMethod() {
        System.out.println("ModelObject....doMethod");
    }

}

装饰者实现接口:
public class Decorator implements ModelMethodInterface {

    private ModelMethodInterface modelMethodInterface;

    Decorator(ModelMethodInterface modelMethodInterface) {
        super();
        this.modelMethodInterface = modelMethodInterface;
    }

    @Override
    public void doMethod() {
        modelMethodInterface.doMethod();
    }

}

继承装饰者:
public class DecoratorA extends Decorator {


    DecoratorA(ModelMethodInterface modelMethodInterface) {
        super(modelMethodInterface);
    }

    @Override
    public void doMethod() {
        // TODO Auto-generated method stub
        super.doMethod();
        System.out.println("DecoratorA....doMethod");
    }
}


继承装饰者:
public class DecoratorB extends Decorator {

    DecoratorB(ModelMethodInterface modelMethodInterface) {
        super(modelMethodInterface);
    }

    @Override
    public void doMethod() {
        super.doMethod();
        System.out.println("DecoratorB....doMethod");
    }
}

测试类:
public class Test {

    public static void main(String[] args) {
        System.out.println("=====================");
        ModelMethodInterface mmif = new ModelObject();
        System.out.println("this is the mmif doMethod");
        mmif.doMethod();
        System.out.println("=====================");
        DecoratorA da = new DecoratorA(mmif);
        System.out.println("this is the DecoratorA doMethod");
        da.doMethod();
        System.out.println("=====================");
        DecoratorB db = new DecoratorB(da);
        System.out.println("this is the DecoratorB doMethod");
        db.doMethod();
    }
}


自我总结:
在最开始编写的时候,总是得不到想要的结果,最后发现在构造函数中使用的不是接口,而是具体类,导致当前方法总是会覆盖掉之前的方法,再次,需要注意这点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值