---
title: "装饰器模式"
author: "return_space"
date: "2012-03-26T22:16:45Z"
tags: []
categories: ["企业架构"]
slug: "untitled"
draft: false
lastmod: "2012-03-25T17:14:32Z"
id: 1463434
url: "https://return-space.iteye.com/blog/1463434"
---

装饰器模式：即客户端先调用的接口A，现在客户端需要在调用接口A的时候，期望A有更多的功能。

 

具体代码如下：

 

```
package com.mkf.pattern;

public interface InterfaceOne {
	public void operation();
}


package com.mkf.pattern.impl;

import com.mkf.pattern.InterfaceOne;

public class Source implements InterfaceOne {

	@Override
	public void operation() {
		System.out.println("源被调用：" + Source.class.getName());
	}

}


package com.mkf.pattern.impl;

import com.mkf.pattern.InterfaceOne;

public class DecoratorOne implements InterfaceOne {
	private InterfaceOne io;

	public DecoratorOne(InterfaceOne io) {
		super();
		this.io = io;
	}

	@Override
	public void operation() {
		System.out.println("DecoratorOne 增强功能前");
		io.operation();
		System.out.println("DecoratorOne 增强功能后");
	}

}


package com.mkf.pattern.impl;

import com.mkf.pattern.InterfaceOne;

public class DecoratorTwo implements InterfaceOne {
	private InterfaceOne io;

	public DecoratorTwo(InterfaceOne io) {
		super();
		this.io = io;
	}

	@Override
	public void operation() {
		System.out.println("DecoratorTwo 增强功能前");
		io.operation();
		System.out.println("DecoratorTwo 增强功能后");
	}

}


package com.mkf.pattern.impl;

import com.mkf.pattern.InterfaceOne;

public class DecoratorThree implements InterfaceOne {
	private InterfaceOne io;

	public DecoratorThree(InterfaceOne io) {
		super();
		this.io = io;
	}

	@Override
	public void operation() {
		System.out.println("DecoratorThree 增强功能前");
		io.operation();
		System.out.println("DecoratorThree 增强功能后");
	}

}


package com.mkf;

import com.mkf.pattern.InterfaceOne;
import com.mkf.pattern.impl.DecoratorOne;
import com.mkf.pattern.impl.DecoratorThree;
import com.mkf.pattern.impl.DecoratorTwo;
import com.mkf.pattern.impl.Source;

public class TestDecorator {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Source s = new Source();
		InterfaceOne io = new DecoratorOne(
				new DecoratorTwo(
						new DecoratorThree(s)));
		io.operation();
	}

}
```

 

输出结果：

 

DecoratorOne 增强功能前  
DecoratorTwo 增强功能前  
DecoratorThree 增强功能前  
源被调用：com.mkf.pattern.impl.Source  
DecoratorThree 增强功能后  
DecoratorTwo 增强功能后  
DecoratorOne 增强功能后