一、装饰模式的定义
装饰模式是一种比较常见的模式,其定义如下:attach additional responsibilities to an object dynamically keeping the same interface.decorators provide a flexible alternative to subclassing for extending functionality.(动态地给一个对象添加额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活)
装饰模式的通用类图如图:
public abstract class component {
//抽象的方法
public abstract void operate();
}
具体构件代码:
public class concretecomponent extends component {
@override
public void operate() {
system.out.println("do somthing");
}
}
抽象装饰者:
public abstract class decorator extends component {
private component component = null;
public decorator(component component) {
this.component = component;
}
@override
public void operate() {
this.component.operate();
}
}
具体装饰类:
public class concretedecorator1 extends decorator {
public concretedecorator1(component component) {
super(component);
}
private void method1() {
system.out.println("method1 修饰");
}
@override
public void operate() {
this.method1();
super.operate();
}
}
public class concretedecorator2 extends decorator {
public concretedecorator2(component component) {
super(component);
}
private void method2() {
system.out.println("method2 修饰");
}
@override
public void operate() {
this.method2();
super.operate();
}
}
场景类:
public class client {
public static void main(string args[]) {
component component = new concretecomponent();
//第一次修饰
component = new concretedecorator1(component);
//第二次修饰
component = new concretedecorator2(component);
//修饰后运行
component.operate();
}
}