设计模式(三)—— 装饰模式

简述

设计模式中的装饰模式,是在已有的功能状态下,向旧的类添加新的功能时,可以避免修改旧代码的设计模式。

例如:一个人,穿衣服、裤子、鞋子…等功能都属于人的装饰,并且每个人选择的装饰可以有区别,可以独立分开和搭配;另外,在购买新的装饰时(新添加新的功能),只需要继承原有的装饰类并实现对应装饰的功能即可,与之前的其他装饰或人完全解藕。

UML图示

代码示例

装饰相关类

/**
 * 装饰器
 * @author: Kellan_Song
 * @date: 2021-01-15 23:58
 **/
public abstract class Decorator {

    Decorator d;

    protected Person show(Person person) {
        if (d != null) {
            d.show(person);
        }
        return person;
    }

    protected void setDecorator(Decorator d) {
        this.d = d;
    }

    Decorator(Decorator d) {
        this.d = d;
    }

    public Decorator(){
    }

}



/**
 * 装饰- T-Shirt
 * @author: Kellan_Song
 * @date: 2021-01-16 00:27
 **/
public class Shirt extends Decorator {

    public Shirt() {

    }

    public Shirt(Decorator t) {
        super(t);
    }

    public Person show(Person person) {
        if (person.name != null) {
            System.out.println(person.name + " 穿T-Shirt");
            super.show(person);
        }
        return person;
    }
}

/**
 * 装饰-鞋子
 * @author: Kellan_Song
 * @date: 2021-01-16 00:29
 **/
public class Shoes extends Decorator {
    ...此处省略...
}

/**
 * 装饰-裤子
 * @author: Kellan_Song
 * @date: 2021-01-16 00:29
 **/
public class Pants extends Decorator {
    ...此处省略...
}

被装饰相关

/**
 * 人类
 * @author: Kellan_Song
 * @date: 2021-01-15 23:38
 **/
public abstract class Person {

    String name;

    public Decorator decorator;

    public Decorator getDecorator() {
        return decorator;
    }

    public Person setDecorator(Decorator decorator) {
        this.decorator = decorator;
        return this;
    }

    public void show() {
        if (decorator != null) {
            decorator.show(this);
        }
    }

}

/**
 * 男人
 * @author: Kellan_Song
 * @date: 2021-01-16 00:09
 **/
public class Man extends Person {

    public Man() {
    }

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

示例

public class Main {

    public static void main(String[] args) {
        Man kellan = new Man("Kellan");
        kellan.setDecorator(new Shirt(new Pants(new Shoes())));
        kellan.show();
    }
}

-- 输出结果
Kellan 穿T-Shirt
Kellan 穿裤子
Kellan 穿鞋子

缺点

每个对应的装饰都需要新建一个类进行独立管理,且类型需要高度一致;若需求改动使其中一个与其他不同,则改动大。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值