设计模式-装饰模式

1.1装饰模式的定义

指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式,它属于对象结构型模式。

1.2 装饰模式的结构

装饰模式主要包含以下角色。

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

在这里插入图片描述

package decorator;
public class DecoratorPattern{
    public static void main(String[] args){
        Component p=new ConcreteComponent();
        p.operation();
        System.out.println("---------------------------------");
        Component d=new ConcreteDecorator(p);
        d.operation();
    }
}
/**
 * 抽象构件角色
 */
interface  Component{
    public void operation();
}
/**
 * 被装饰者
 */
class ConcreteComponent implements Component{
    public ConcreteComponent(){
        System.out.println("创建具体构件角色");       
    }   
    public void operation(){
        System.out.println("调用具体构件角色的方法operation()");           
    }
}
/**
 * 抽象装饰者
 */
class Decorator implements Component{
    private Component component;   
    public Decorator(Component component){
        this.component=component;
    }   
    public void operation(){
        component.operation();
    }
}
/**
 * 具体装饰者
 */
class ConcreteDecorator extends Decorator{
    public ConcreteDecorator(Component component){
        super(component);
    }   
    public void operation(){
        super.operation();
        addedFunction();
    }
    public void addedFunction(){
        System.out.println("为具体构件角色增加额外的功能addedFunction()");           
    }
}

程序运行结果如下:

创建具体构件角色
调用具体构件角色的方法operation()
---------------------------------
调用具体构件角色的方法operation()
为具体构件角色增加额外的功能addedFunction()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值