首页 > 其他 > 详细

装饰(Decorator)模式

时间:2020-06-25 18:52:11      阅读:57      评论:0      收藏:0      [点我收藏+]

 

名称:

    装饰模式(Decorator Pattern)

 

问题:

Wikipedia:

The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases at run-time, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.

This pattern is designed so that multiple decorators can be stacked on top of each other, each time adding a new functionality to the overridden method(s).

 

解决方案:

    

1、 模式的参与者

    1、Component

    -定义一个对象接口,可以给这些对象动态地添加职责。

    2、ConcreteComponent

    -定义一个对象,可以给这个对象添加一些职责。

   3、Decorator

    -维持一个指向Component对象的指针,并定义一个于Component接口一致的接口。

    4、ConcreteDecorator

    -向组件添加职责。

2.实现方式

    

interface  Component
{
    public void operation();
}
class ConcreteComponent implements Component
{   
    public void 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();
        decoratorFunction();
    }
    public void decoratorFunction()
    {
           
    }
}

 

装饰模式在java中的最著名的应用: Java I/O 标准库。

 

参考资料

《设计模式:可复用面向对象软件的基础》

装饰(Decorator)模式

原文:https://www.cnblogs.com/diameter/p/13192277.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!