装饰者模式又称为包装(wrapper)模式。装饰者模式对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。

结构:

  装饰者模式以透明的方式给一个对象附加上更多的责任,换而言之,客户端并不会觉得对象在装饰前后有什么不同,装饰者模式可以在不使用创造更多子类的情况下,将对象的功能拓展。

结构图:

一天一个设计模式:装饰者模式

角色分析:

    抽象构件(Component)角色:给出一个抽象接口,以规范准备接受附加责任的对象。

  具体构件(ConCreteComponent)角色:定义一个将要接受附加责任的类。

  装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。

  具体装饰(ConcreteDecorator)角色:负责给构件对象“贴上”附加的责任。

代码:

抽象构建角色:

public interface Component {
    
    public void sampleOperation();
    
}
View Code

具体构件角色:

public class ConcreteComponent implements Component {

    @Override
    public void sampleOperation() {
        // 写相关的业务代码
    }

}
View Code

装饰者角色:

public class Decorator implements Component{
    private Component component;
    
    public Decorator(Component component){
        this.component = component;
    }

    @Override
    public void sampleOperation() {
        // 委派给构件
        component.sampleOperation();
    }
    
}
View Code

具体装饰者角色:

public class ConcreteDecoratorA extends Decorator {

    public ConcreteDecoratorA(Component component) {
        super(component);
    }
    
    @Override
    public void sampleOperation() {
     super.sampleOperation();
        // 写相关的业务代码
    }
}
//B组件类似

具体示例

有工人接口,我们定义了铁匠,现在要对铁匠进行不同的技能强化。

工人接口:

public interface Worker {

    void working();
}
View Code

铁匠实现类:

public class Smith implements Worker {

    private String name;

    private int age;

    public Smith(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public void working() {
        System.out.println("我是一个铁匠");
    }
}
View Code

技能实现类:

public class Skill implements Worker {
    private Worker worker;

    public Skill(Worker worker) {
        this.worker = worker;
    }

    @Override
    public void working() {
        worker.working();
    }

    //为半透明模式做的拓展
    public void heating(){}
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-04
  • 2021-12-29
  • 2021-10-05
猜你喜欢
  • 2021-10-10
  • 2022-12-23
  • 2021-10-15
  • 2021-07-24
  • 2021-05-25
相关资源
相似解决方案