功能放在单独的类,并让这个类包装它所要修饰的对象。
添加的新功能,而这些新功能只是为了对曾经的主类做一些修饰,只在特定情况下才会执行的特殊行为。这些新功能代码当然可以添加到原有的主类里,但是这一方面违背了开放-封闭原则,另一方面,也增加了主类的复杂性。这时,通过使用装饰模式,增加一些新类,从而实现有选择且按顺序的包装对象。
添加职责。
添加一些职责。
功能。
添加职责的功能。
/**
/**
-
@Author: cxh
-
@CreateTime: 18/1/2 21:22
-
@ProjectName: JavaBaseTest
*/
public class Decorator extends Person {
protected Person person;
Decorator(){}
public void decorator(Person person){
this.person=person;
}
@Override
public void operation() {
if(person!=null)
person.operation();
}
}
/**
/**
/**
/**
-
@Author: cxh
-
@CreateTime: 18/1/2 21:38
-
@ProjectName: JavaBaseTest
*/
public class Client {
//测试类
public static void main(String[] args) {
Person person=new Person("朱莉");
TShirts tShirts=new TShirts();
Pants pants=new Pants();
Shoes shoes=new Shoes();
tShirts.decorator(person);
pants.decorator(tShirts);
shoes.decorator(pants);
shoes.operation();
}
}
输出:
Process finished with exit code 0