装饰器模式

2019-07-22  本文已影响0人  ppamos

装饰模式的定义与特点

通常情况下,扩展一个类的功能会使用继承方式来实现。但继承具有静态特征,耦合度高,并且随着扩展功能的增多,子类会很膨胀。如果使用组合关系来创建一个包装对象(即装饰对象)来包裹真实对象,并在保持真实对象的类结构不变的前提下,为其提供额外的功能,这就是装饰模式的目标。下面来分析其基本结构和实现方法

1.模式的结构
装饰模式主要包含以下角色。
1.抽象构件(Component)角色:定义一个抽象接口以规范准备接收附加责任的对象。
2.具体构件(Concrete Component)角色:实现抽象构件,通过装饰角色为其添加一些职责。
3.抽象装饰(Decorator)角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
4.具体装饰(ConcreteDecorator)角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。

2.模式的实现

public interface Component
{
     void operation();
}
public class ConcreteComponent implements Component
{
    public ConcreteComponent()
    {
        System.out.println("创建具体的构建角色");
    }

    @Override
    public void operation()
    {
        System.out.println("调用具体角色构建方法");
    }
}
class Decorator implements Component
{
    private Component component;
    public Decorator(Component component)
    {
        this.component=component;
    }
    public void operation()
    {
        component.operation();
    }
}
public class ConcreteDecorator extends Decorator
{
    public ConcreteDecorator(Component component)
    {
        super(component);
    }

    @Override
    public void operation()
    {
        super.operation();
        addOperation();
    }

    private void addOperation(){
        System.out.println("添加的方法");
    }
}
public class ConcreteDecorator extends Decorator
{
    public ConcreteDecorator(Component component)
    {
        super(component);
    }

    @Override
    public void operation()
    {
        super.operation();
        addOperation();
    }

    private void addOperation(){
        System.out.println("添加的方法");
    }
}
创建具体的构建角色
调用具体角色构建方法
添加的方法

装饰模式的应用场景

前面讲解了关于装饰模式的结构与特点,下面介绍其适用的应用场景,装饰模式通常在以下几种情况使用。

上一篇 下一篇

猜你喜欢

热点阅读