在不改变现有对象类结构的前提下,添加新的功能,避免通过继承为类引入静态特征,防止随着扩展功能的增多,子类会很膨胀。
角色
抽象构件(Component):装饰类和被装饰类的公共接口
具体构件(Concrete Component):被装饰类
抽象装饰(Decorator):抽象装饰类,包含被装饰类的实例,可以通过其子类扩展被装饰类的功能
具体装饰(Concrete Decorator):实现抽象装饰类的相关方法,为被装饰类扩展新的功能
抽象构件 Component
public interface Component {
void operation();
}
具体构件 ConcreteComponent
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("component operation...");
}
}
抽象装饰 Decorator
public abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
public void handle() {
System.out.println("public handle...");
}
}
具体装饰 Concrete Decorator
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
@Override
public void operation() {
component.operation();
System.out.println("decorator component...");
}
public void newFunction() {
System.out.println("new function...");
}
}
测试类
public class DecoratorTester {
public static void main(String args[]) {
Component component = new ConcreteComponent();
ConcreteDecorator decorator = new ConcreteDecorator(component);
decorator.operation();
decorator.handle();
decorator.newFunction();
}
}
component operation...
decorator component...
public handle...
new function...
举例
狗能跑、叫、跳,为泰迪通过装饰器模式添加直立行走的行为
抽象构件 Dog
public interface Dog {
void run();
void bark();
void jump();
}
具体构件 Teddy
public class Teddy implements Dog {
private String name;
public Teddy(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println(toString() + " run");
}
@Override
public void bark() {
System.out.println(toString() + " bark");
}
@Override
public void jump() {
System.out.println(toString() + " jump");
}
@Override
public String toString() {
return String.format("Teddy %s", name);
}
}
抽象装饰 DogDecorator
抽象装饰(DogDecorator)实现抽象构建(Dog)接口,并通过持有具体构建(Teddy)实例,可扩展 / 改变 具体构建原有的行为
public abstract class DogDecorator implements Dog {
protected Dog dog;
public DogDecorator(Dog dog) {
this.dog = dog;
}
@Override
public void run() {
//do something...
dog.run();
}
@Override
public void bark() {
//do something...
dog.bark();
}
@Override
public void jump() {
//do something...
dog.jump();
}
}
具体装饰 TeddyDecorator
继承实现抽象装饰(DogDecorator),添加新功能 walkUpright
public class TeddyDecorator extends DogDecorator {
public TeddyDecorator(Dog dog) {
super(dog);
}
public void walkUpright() {
System.out.println(dog.toString() + " walk upright");
}
}
public class DogDecoratorTester {
public static void main(String args[]) {
Dog teddy = new Teddy("Diandian");
teddy.jump();
teddy.bark();
TeddyDecorator teddyDecorator = new TeddyDecorator(teddy);
teddyDecorator.walkUpright();
}
}
Teddy Diandian jump
Teddy Diandian bark
Teddy Diandian walk upright
参考:
http://c.biancheng.net/view/1366.html
https://www.cnblogs.com/jzb-blog/p/6717349.html