1.装饰模式介绍
每个人都有着各式各样的装扮,但是不论你的穿着怎么样,但是个人的本质确实不变的,这就是装饰模式,装饰物也许各不相同,但是对象的本质是不变的。
2.装饰模式的定义
动态的给一个对象添加一些额外的职责,动态的扩展一个类。装饰模式比继承更为灵活。
3.遵循的设计原则
多用组合,少用继承。利用继承设计子类的行为,是在编译时静态决定的,而且所有的子类都会继承到相同的行为。然而。如果能够利用组合的做法扩展对象的行为,就可在运行时动态地进行扩展。
类应该设计成对外扩展开放,对修改关闭。
4.实现
Component(抽象构件):可以是一个接口或是抽象类,其充当的是被装饰的原始对象
Concrete Component(具体构件):该类是Component类的基本实现,也是我们装饰的具体对象
Decorator(抽象装饰类):装饰我们的组件对象,其内部一定要有一个指向组件对象的引用,通过该引用可以调用装饰之前构件的方法,并通过其子类扩展该方法。
Concreate Decorator(具体装饰类):装饰者具体实现类。只对抽象装饰者作出具体的实现。
先定义一个Component,可以是接口也可以是抽象类:
public interface Component{
//你也可以增加更多的方法
void operation();
}
接下来是ConcreateComponent:
public class ConcreteComponent implements Component{
public void operation(){
<span style="white-space:pre"> </span>//具体逻辑,这个随你做
}
}
Decorator:
public abstract class Dectorator implements Component{
//持有一个Component对象的引用
private Component component;
//必要的构造方法,需要一个Component类型的对象
public Dectrator(Component component){
this.component = component;
}
public void operation(){
component.operation();
}
}
ConcreateDecorator:
public class ConcreteDecoratorA extends Decorator{
public void operate(){
operateA();
super.operation();
operateB();
}
//自定义的装饰方法A
public void operateA(){
<span style="white-space:pre"> </span>//装饰方法逻辑
}
//自定义的装饰方法B
public void operateB(){
//装饰方法逻辑
}
}
客户端调用类:
public class Client{
public static void main(String[] args){
Component component = new Component();
Decorator decorator = new ConcreteDecoratorA(component);
decorator.operate();
}
}
java中API中的流也有装饰者的影子:
1.继承自InputStream/OutputStream的流都是用于向程序中输入/输出数据,且数据的单位都是字节。其中,FileInputStream、PipedInputStream等都是组件(InputStream[])具体的实现类。FilterInputStream是抽象装饰者,BufferedInputStream、DataInputStream等都是具体装饰者。