其实装饰者模式就是给组件或者被装饰的对象扩展功能的,不同于单纯的继承关系,装饰者比子类更加的灵活,更容易组装
并且装饰之后是带有之前被装饰的功能的,不像子类的比较散的
这里举一个例子
一个人穿衣服
如果是一般的解决方案是创造一个Person类,定义几个方法,穿鞋子穿衣服等等,然而如果在要添加新的衣服的时候,就必须要修改Person,即违背了开放封闭原则
如果遵守开放封闭原则,则可以设计一个穿衣服的接口,让各种衣服实现这个接口或者抽象类,添加新衣服只需要继承或者实现接口即可,然而这样穿衣服没有逻辑性,零散的
如果采用装饰者模式
被装饰的类完全不知道有装饰者的存在,在装饰者的类中添加一个被装饰者属性,并在其中添加为被装饰者赋值的方法,让其他具体的装饰者来继承这个装饰类
其中类包括:
Person类(被装饰者)
Decorator(装饰者基类,其中有一个被装饰者属性,和对应的设置方法)
Xiezi(Decorator的子类,属于具体的装饰者)
Tixue(Decorator的子类,属于具体的装饰者)
Person类,被装饰者类
package decorator;
public class Person {
private String name;
public Person() {
// TODO 自动生成的构造函数存根
}
public Person(String name){
this.name=name;
}
public void Show(){
System.out.println("装扮:"+name);
}
}
Decorator,装饰者基类
package decorator;
public class Decorator extends Person{
private Person person;
public Decorator(){
}
public Decorator(Person person){
this.person = person;
}
public void SetDecorator(Person person){
this.person = person;
}
@Override
public void Show() {
// TODO 自动生成的方法存根
if(person!=null){
person.Show();
}
}
}
具体装饰者类,鞋子类
package decorator;
public class Xiezi extends Decorator {
@Override
public void Show() {
// TODO 自动生成的方法存根
super.Show();
System.out.println("穿鞋子");
}
}
具体装饰者类,T恤类
package decorator;
public class Tixue extends Decorator{
@Override
public void Show() {
// TODO 自动生成的方法存根
super.Show();
System.out.println("穿T恤");
}
}
测试代码
package decorator;
public class Test {
@org.junit.Test
public void test() {
Person person =new Person("小明");
Tixue tixue = new Tixue();
Xiezi xiezi = new Xiezi();
tixue.SetDecorator(person);
tixue.Show();
xiezi.SetDecorator(tixue);
xiezi.Show();
}
}
测试结果
装扮:小明
穿T恤
穿鞋子