设计原理
类应该对扩展开放,对修改关闭(会增加复杂度)
定义
动态地将责任附加到对象上,若要扩展,它提供比继承更有弹性
类图
写了一个简单例子(用来装饰人)
须要被装饰的类(一个人)
public class AveragePerson implements Person{
public String printPerson() {
return "人";
}
}
我们须要装饰printPerson方法就须要提一个接口Person
public interface Person {
public String printPerson();
}
现在把须要提出来的公共代码提到抽象类中
public abstract class PersonImpl implements Person {
public Person person;
public abstract String printPerson();
}
下面是装饰类,它实现了抽象类(即与被装饰类有相同接口)
男人:
public class Man extends PersonImpl{
public Man(Person person) {
this.person=person;
}
@Override
public String printPerson() {
return "男"+person.printPerson();
}
}
女人
public class Woman extends PersonImpl {
public Woman(Person person) {
this.person = person;
}
@Override
public String printPerson() {
return "女" + person.printPerson();
}
}
测试代码
public class Main {
public static void main(String[] args) {
System.out.println(new Man(new AveragePerson()).printPerson());
System.out.println(new Woman(new AveragePerson()).printPerson());
System.out.println(new Woman(new Man(new AveragePerson())).printPerson());
}
}