解決的問(wèn)題
為一個(gè)類添加更多功能茎杂。簡(jiǎn)單的情形可以使用繼承。有些復(fù)雜的情況使用繼承就比較麻煩了纫雁。例如要開(kāi)發(fā)一個(gè)保存數(shù)據(jù)到云端的功能(CloudStream)煌往,有些數(shù)據(jù)可以要先加密再保存,有些數(shù)據(jù)可能要先壓縮再保存轧邪,有些數(shù)據(jù)可能要壓縮并且加密再保存刽脖,諸如此類。這時(shí)用Decorator Pattern(裝飾模式)會(huì)比較好忌愚。
代碼
Stream
:
package com.cong.designpattern.decorator;
public interface Stream {
public void write(String data);
}
CloudStream
:
package com.cong.designpattern.decorator;
public class CloudStream implements Stream{
@Override
public void write(String data) {
System.out.println("Write " + data);
}
}
EncryptedStream
:
package com.cong.designpattern.decorator;
public class EncryptedStream implements Stream{
private Stream stream;
public EncryptedStream(Stream stream) {
this.stream = stream;
}
@Override
public void write(String data) {
String encrypted = data + "[encrypted]";
this.stream.write(encrypted);
}
}
CompressedStream
:
package com.cong.designpattern.decorator;
public class CompressedStream implements Stream{
private Stream stream;
public CompressedStream(Stream stream) {
this.stream = stream;
}
@Override
public void write(String data) {
String compressed = data + "[compressed]";
this.stream.write(compressed);
}
}
Test code:
CloudStream cloudStream = new CloudStream();
EncryptedStream encryptedStream = new EncryptedStream(cloudStream);
CompressedStream compressedStream = new CompressedStream(encryptedStream);
compressedStream.write("1234567890");