大话设计模式之装饰模式(Java总结)

设计模式之装饰模式

前言

  在开发过程中,我们会遇到要将某一个功能赋予额外的职责,并把这些增加了额外职责的功能按照正确的顺序串联起来进行控制,且可以灵活地调换这些顺序,输出最后执行的结果,装饰模式就是这样一个非常有意思的设计模式。

场景

  衣服、鞋子、领带、披风都可以理解为对人的装饰。而且可以选择先穿衣服再穿鞋子,或者先穿鞋子,再穿衣服

策略模式

  动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
在这里插入图片描述

代码示例

Person类(ConcreteComponent)

public class Person {

    private String name;

    public Person(){}

    public Person(String name){
        this.name = name;
    }

    public void show(){
        System.out.println("装扮的" + name);
    }
}

服饰类(Decorator)

public class Finery extends Person{

    protected Person component;

    /**
     * 打扮
     *
     * @param component
     */
    public void decorate(Person component){
        this.component = component;
    }

    @Override
    public void show(){
        if (null != component){
            component.show();
        }
    }

}

具体服饰类(ConcreteDecorator)

public class TShirts extends Finery {

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

}

public class BigTrouser extends Finery {

    @Override
    public void show(){
        System.out.println("垮裤");
        super.show();
    }

}

//其余类类似,省略
..........

客户端

public class Main {

    public static void main(String[] args) {

        Person person = new Person("Java_Mike");

        System.out.println("第一种装扮");

        Sneakers sneakers = new Sneakers();
        BigTrouser bigTrouser = new BigTrouser();
        TShirts tShirts = new TShirts();

        sneakers.decorate(person);
        bigTrouser.decorate(sneakers);
        tShirts.decorate(bigTrouser);
        tShirts.show();

        System.out.println("第二种装扮");
        LeatherShoes leatherShoes = new LeatherShoes();
        Tie tie = new Tie();
        Suit suit = new Suit();
        leatherShoes.decorate(person);
        tie.decorate(leatherShoes);
        suit.decorate(tie);
        suit.show();

    }
}

运行结果
在这里插入图片描述

优点

  1. 把类中的装饰功能从类中搬移去除,这样可以简化原有的类
  2. 有效地把类的核心职责和装饰功能区分开了。而且可以去除相关类中重复的装饰逻辑。

参考资料
[1]: 大话设计模式 程杰著 清华大学出版社
[2]: https://blog.csdn.net/wwwdc1012/article/details/82764333

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值