装饰模式
在不想增加很多子类的情况下扩展类时
1.接口
public abstract class Component {
public abstract void operation();
}
2.实现的对象
public class ConcreteComponent extends Component {
@Override
public void operation() {
System.out.println("具体对象的操作");
}
}
3.装饰类,
public class Decorator extends Component {
private Component component = null;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
if (component != null) {
this.component.operation();
}
}
}
4.继承的装饰类A
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
//定义自己的修饰方法
private void method1() {
System.out.println("method1 修饰");
}
@Override
public void operation() {
this.method1();
super.operation();
}
}
5.继承的装饰类B
public class ConcreteDecoratorB extends Decorator {
//定义被修饰者
public ConcreteDecoratorB(Component component) {
super(component);
}
//定义自己的修饰方法
private void method2() {
System.out.println("method2 修饰");
}
@Override
public void operation() {
super.operation();
this.method2();
}
}
6.创建一个需要装饰的对象, 将需要装饰的对象放到装饰类中,返回被装饰的对象.
public class Test {
public void test() {
Component component = new ConcreteComponent();
//第一次修饰
component = new ConcreteDecoratorA(component);
//第二次修饰
component = new ConcreteDecoratorB(component);
//修饰后运行
component.operation();
}
}