【设计模式】结构型02装饰模式(Decorator Pattern)

时间:2021-12-10 16:31:40

装饰模式(Decorator Pattern)


意图:动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。

主要解决:一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。

何时使用:在不想增加很多子类的情况下扩展类。

以下是demo:

这里我省略了消费者House类,直接使用核心实现方式进行解释:

1、装饰类接口与装饰对象:

package com.pat.decorator;
/**
* 装饰类接口-所有装饰类实现本接口
* @author ZX
*
*/
public interface Decorator{
void decorat();
} /**
* 下面是所有的装饰对象,各自持有一个(根据实际情况)装饰对象
* @author ZX
*
*
*/
class Sofa implements Decorator{
private Decorator decorator; @Override
public void decorat() {
if(decorator!=null)
decorator.decorat();
System.out.println("装沙发"); }
public Sofa() {}
public Sofa(Decorator decorator) {
this.decorator=decorator;
} }
class Desk implements Decorator{
private Decorator decorator;
@Override
public void decorat() {
if(decorator!=null)
decorator.decorat();
System.out.println("装桌子"); }
public Desk() {}
public Desk(Decorator decorator) {
this.decorator=decorator;
}
}
package com.pat.decorator;

public class Test {
public static void main(String[] args) {
Sofa sofa = new Sofa();
Desk desk = new Desk(sofa);
Computer com = new Computer(desk);
com.decorat();
}
}

class Computer implements Decorator{private Decorator decorator;@Overridepublic void decorat() {if(decorator!=null)decorator.decorat();System.out.println("装电脑");}public Computer() {}public Computer(Decorator decorator) {this.decorator=decorator;}}

2、测试类:

package com.pat.decorator;

public class Test {
public static void main(String[] args) {
Sofa sofa = new Sofa();
 Desk desk = new Desk(sofa);
Computer com = new Computer(desk);
com.decorat();
}
}