装饰者模式

概念

什么是装饰者模式?

动态的给一个对象添加额外的职责或功能。在添加一种额外职责或功能的时候并不修改该对象的类,满足了开闭原则。大致类图如下
这里写图片描述

代码实现

案例场景

假如我们需要给一个人进行装扮,例如穿什么衣服、裤子、鞋子等。如果我们需要做到能够随意的给人进行搭配,那么改怎样通过代码实现呢?这时候就可以用到装饰者模式。具体代码如下:

Component类
public abstract class PersonComponent { 
    public abstract void show();
}
ConcreteComponent类
public class Student extends PersonComponent{

    private String mName;

    public Student(String name){
        this.mName = name;
    }

    @Override
    public void show() {
        System.out.println(this.mName+"穿的是: ");
    }

}
Decorator类
public abstract class BaseDecorator extends PersonComponent{

    protected PersonComponent mComponent;

    public BaseDecorator(PersonComponent component){
        this.mComponent = component;
    }

}
ConcreteDecoratorA
public class TShirts extends BaseDecorator{

    public TShirts(PersonComponent component) {
        super(component);
    }

    @Override
    public void show() {
        this.mComponent.show();
        System.out.println("T 恤");
    }

}
ConcreteDecoratorB
public class Cowboy extends BaseDecorator{

    public Cowboy(PersonComponent component) {
        super(component);
    }

    @Override
    public void show() {
        this.mComponent.show();
        System.out.println("牛仔");
    }

}
客户端代码
public class TestMain {

    public static void main(String[] args){
        PersonComponent studentA = new Student("张山");
        TShirts tShirtsA = new TShirts(studentA);
        Cowboy cowboyA = new Cowboy(tShirtsA);
        cowboyA.show();


        PersonComponent studentB = new Student("李四");
        TShirts tShirtsB = new TShirts(studentB);
        tShirtsB.show();
    }

}

输出:
张山说我穿的是: 
T 恤
牛仔
李四说我穿的是: 
T 恤

总结

1、装饰者模式它可以很好的做到为已有的功能动态的添加更多功能,并满足开闭原则;
2、把类中的装饰功能从类中搬除,很好的简化了原来的类。

参考文献

《大话设计模式》
https://blog.csdn.net/gdutxiaoxu/article/details/51885105

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值