您的位置:首页 > 编程语言 > Java开发

Java设计模式(7)—— 装饰器

2009-08-21 18:13 726 查看
Decorator

英文简单描述

Intent

Attach additional responsibilities to an object dynamically.

Decorators provide a flexible alternative to subclassing for extending functionality.

How to

The decorator conforms to the interface of the component it decorates

so that its presence is transparent to the component's clients.

Component

defines the interface for objects that can have responsibilities added to them dynamically.

ConcreteComponent

defines an object to which additional responsibilities can be attached.

Decorator

maintains a reference to a Component object and defines an interface that conforms to Component's interface.

ConcreteDecorator

adds responsibilities to the component.

Known cases

Java IO Stream

GUI

UML






好处:

(1)比静态的继承更灵活 [More flexibility than static inheritance]



(2)保持组件轻量级 [Keeping Component classes lightweight]

(3)和策略区别:

A decorator lets you change the skin of an object; a strategy lets you change the guts. These are two alternative ways of changing an object.



代码:

public interface ILogger {
void logger(String info);
}
public class ConsoleLogger implements ILogger {
public void logger(String info) {
System.out.println(info);
}

}
public class FileLogger implements ILogger {
private PrintWriter writer;

public FileLogger(String path) {
File file = new File(path);
FileOutputStream output;
try {
output = new FileOutputStream(file);
writer = new PrintWriter(output);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

public void logger(String info) {
if (writer == null) {
System.out.println("FileLogger init failure");
} else {
writer.write(info);
writer.flush();
}
}
}
public abstract class DecoratorLogger implements ILogger {

protected ILogger delegate;
public DecoratorLogger(ILogger delegate) {
this.delegate = delegate;
}
abstract public void logger(String info);
}
public class EncryptLogger extends DecoratorLogger {
public EncryptLogger(ILogger delegate) {
super(delegate);
}
public void logger(String info) {
String temp = encrypt(info);
delegate.logger(temp);
}

private String encrypt(String info) {
// encrypt algorithm
// ...
return info;
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: