大话设计模式-装饰模式
/**
* 被装饰的对象接口 可以给继承自此类的子对象动态的添加职责
*/
public abstract class Component {
public abstract void Operation();
}
/**
* 具体的对象 可以给其动态的添加职责
*/
public class ConcreteComponent extends Component {
@Override
public void Operation() {
System.out.println("具体对象的操作");
}
}
/**
* 具有装饰功能的类 可以给Component的子类动态的添加职责
*/
public class Decorator extends Component {
protected Component component;
public Decorator() {
}
public Decorator(Component component) {
this.component = component;
}
public void setComponent(Component component) {
this.component = component;
}
@Override
public void Operation() {
if (component != null) {
component.Operation();
}
}
}
/**
* 具体的装饰类 给Component的子类添加A职责
*/
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA() {
super();
}
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void Operation() {
super.Operation();
System.out.print("具体装饰对象A的操作->");
initA();
}
private void initA() {
System.out.println("A类独有的方法,区别于B类");
}
}
/**
* 具体的装饰类 给Component的子类添加B职责
*/
public class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB() {
}
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void Operation() {
super.Operation();
System.out.print("具体装饰对象B的操作->");
initB();
}
private void initB() {
System.out.println("B类独有的方法,区别于A类");
}
}
public class Main {
public static void main(String[] args) {
//第一种创建方法
//concreteComponent 是被装饰的对象 下面将为其添加AB职责
ConcreteComponent concreteComponent = new ConcreteComponent();
ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA();
ConcreteDecoratorB concreteDecoratorB = new ConcreteDecoratorB();
concreteDecoratorA.setComponent(concreteComponent);
concreteDecoratorB.setComponent(concreteDecoratorA);
concreteDecoratorB.Operation();
//第二种创建方法
ConcreteDecoratorB b =
new ConcreteDecoratorB(
new ConcreteDecoratorA(
new ConcreteComponent()));
b.Operation();
}
}