装饰模式:是指在不改变原有对象的基础之上,将功能附加到对象上,提供了比继承更有弹性的替代方案。
装饰模式中的角色:
装饰模式的简单实现:
package cn.sun.code.six.decorator;
abstract class Component {
public abstract void operation();
}
class ConcreteComponent extends Component {
@Override
public void operation() {
System.out.println("具体对象的操作");
}
}
abstract class Decorator extends Component{
protected Component component;
public void setComponent(Component component) {
this.component = component;
}
// 重写Operation(),实际执行的是Component的Operation()
@Override
public void operation() {
component.operation();
}
}
class ConcreteDectatorA extends Decorator {
// 本类独有的功能,以区别于ConcreteDectatorB
private String addedState;
// 首先运行原Component的Operation(),再执行本类的功能,如addState,相当于对原Component进行了装饰
@Override
public void operation() {
super.operation();
addedState = "New State";
System.out.println("具体装饰对象A的操作");
}
}
class ConcreteDectatorB extends Decorator {
@Override
public void operation() {
super.operation();
addedBehavior();
System.out.println("具体装饰对象B的操作");
}
// 本类独有的方式,以区别于ConcreteDectatorA
private void addedBehavior(){
}
public static void main(String[] args) {
ConcreteComponent c = new ConcreteComponent();
ConcreteDectatorA d1 = new ConcreteDectatorA();
ConcreteDectatorB d2 = new ConcreteDectatorB();
// 装饰的方法是:首先用ConcreteComponent实例化对象c,然后用ConcreteDecoratorA的
// 实例化对象d1来包装c,再用COncreteDecoratorB的对象d2来包装d1,最终执行d2的Operation()
d1.setComponent(c);
d2.setComponent(d1);
d2.operation();
}
}
具体对象的操作
具体装饰对象A的操作
具体装饰对象B的操作
public abstract class InputStream implements Closeable {
// SKIP_BUFFER_SIZE is used to determine the size of skipBuffer
private static final int SKIP_BUFFER_SIZE = 2048;
// skipBuffer is initialized in skip(long), if needed.
private static byte[] skipBuffer;
...
}
public
class FileInputStream extends InputStream
{
/* File Descriptor - handle to the open file */
private FileDescriptor fd;
private FileChannel channel = null;
...
}
public
class FilterInputStream extends InputStream {
/**
* The input stream to be filtered.
*/
protected volatile InputStream in;
...
}
public
class BufferedInputStream extends FilterInputStream {
private static int defaultBufferSize = 8192;
/**
* The internal buffer array where the data is stored. When necessary,
* it may be replaced by another array of
* a different size.
*/
protected volatile byte buf[];
...
}
适配器模式也是一种包装模式,它们的区别如下:
原文:https://www.cnblogs.com/riders/p/12197333.html