装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
以一个Person对象为例。Person作为一个接口,Student(学生)和Doctor(医生)为Person接口的两个具体类,DecoratorPerson为Person的装饰类,可对具体类进行装饰。ShoeDecorator(鞋子装饰类)和DressDecorator(衣服装饰类)为具体的装饰类。这个案例可对学生和医生进行装饰。
具体代码:
Person:
public interface Person {
void description();
}
Student:
public class Student implements Person {
@Override
public void description() {
System.out.println("学生");
}
}
Doctor:
public class Doctor implements Person {
@Override
public void description() {
System.out.println("医生");
}
}
DecoratePerson:
public class DecoratePerson implements Person {
private Person person;
public DecoratePerson(Person person) {
this.person = person;
}
@Override
public void description() {
person.description();
}
}
ShoeDecorate:
public class ShoeDecorate extends DecoratePerson {
public ShoeDecorate(Person person) {
super(person);
}
@Override
public void description() {
super.description();
System.out.println("穿鞋子");
}
}
DressDecorate:
public class DressDecorate extends DecoratePerson {
public DressDecorate(Person person) {
super(person);
}
@Override
public void description() {
super.description();
System.out.println("穿衣服");
}
}
测试类:根据装饰的顺序和对象不同,呈现不同的结果和顺序
?
?
|