---
title: "设计模式之装饰模式（Decorator）"
author: "niedashun1"
date: "2008-11-17T22:46:02Z"
tags: []
slug: "decorator"
draft: false
lastmod: "2008-11-17T22:50:58Z"
id: 269115
url: "https://javamy.iteye.com/blog/269115"
---

装饰模式基本上由四部分组成，简单的分为，抽象构件，简单构件，抽象装饰角色，具体装饰角色。下面为是简单说明例子。

 

   抽象构件:Component.java

```
package com.javapatterns.decorator;

public interface Component
{
    void sampleOperation();
}
```

 

 

  具体构件：ConcreteComponent .java

```
package com.javapatterns.decorator;

public class ConcreteComponent implements Component
{
    public void sampleOperation()
    {
        // Write your code here
    }
}
```

 

 

   抽象装饰角色:Decorator.java

```
package com.javapatterns.decorator;

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

    public Decorator() {
    }

    public void sampleOperation()
    {
        component.sampleOperation();
    }

    /**
     * @link aggregation 
     */
    private Component component;
}
```

 

 

   具体装饰角色:

```
package com.javapatterns.decorator;

public class ConcreteDecorator extends Decorator
{
    public void sampleOperation()
    {
        super.sampleOperation();
    }
}
```

 

  

   客户端类：

```
package com.javapatterns.client

import junit.framework.TestCase;

public  class  Client   extends  TestCase{

         public  testDecorator(){
                  new ConcreteDecorator(
                          new ConcreteComponent ();
                  );
        }
}
```

 

  装饰模式其实我们用的十分普遍，象io流，无论是对字节流，字符流，文件流，管道流，还是序列化对象的操作，我们都

  用到他。