前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【设计模式】—— 装饰模式Decorator

【设计模式】—— 装饰模式Decorator

作者头像
用户1154259
发布2018-01-18 12:41:53
5290
发布2018-01-18 12:41:53
举报

  模式意图

  在不改变原来类的情况下,进行扩展。

  动态的给对象增加一个业务功能,就功能来说,比生成子类更方便。

  应用场景

  1 在不生成子类的情况下,为对象动态的添加某些操作。

  2 处理一些可以撤销的职责。

  3 当不能使用生成子类来扩充时。

  模式结构

Component 外部接口,用于定义外部调用的形式。提供默认的处理方法。

代码语言:javascript
复制
interface Component{
     public void operation();
 }

ConcreteComponent  具体的处理类,用于实现operation方法。

代码语言:javascript
复制
class ConcreteComponent implements Component{

    @Override
    public void operation() {
        // TODO Auto-generated method stub
        System.out.println("ConcreteComponent operation()");
    }
    
}

Decorator 装饰类,内部关联一个component对象,调用其operation方法,并添加自己的业务操作。

代码语言:javascript
复制
class Decorator implements Component{
    private Component component;
    @Override
    public void operation() {
        // TODO Auto-generated method stub
        System.out.println("before decorator!");
        component.operation();
        System.out.println("after decorator!");
    }
    public Decorator() {
        // TODO Auto-generated constructor stub
    }
    public Decorator(Component component){
        this.component = component;
    }
    
}

  全部代码

代码语言:javascript
复制
 1 package com.xingoo.decorator;
 2 interface Component{
 3     public void operation();
 4 }
 5 class ConcreteComponent implements Component{
 6 
 7     @Override
 8     public void operation() {
 9         // TODO Auto-generated method stub
10         System.out.println("ConcreteComponent operation()");
11     }
12     
13 }
14 class Decorator implements Component{
15     private Component component;
16     @Override
17     public void operation() {
18         // TODO Auto-generated method stub
19         System.out.println("before decorator!");
20         component.operation();
21         System.out.println("after decorator!");
22     }
23     public Decorator() {
24         // TODO Auto-generated constructor stub
25     }
26     public Decorator(Component component){
27         this.component = component;
28     }
29     
30 }
31 
32 
33 public class test {
34     public static void main(String[] args) {
35         Component component = new Decorator(new ConcreteComponent());
36         component.operation();
37     }
38 }

  运行结果

代码语言:javascript
复制
before decorator!
ConcreteComponent operation()
after decorator!
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2014-10-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  •   模式意图
  •   应用场景
  •   模式结构
  •   全部代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档