装饰模式
概念
装饰模式指的是在不必改变原类文件的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
使用组合实现装饰模式
graph TD
A[公共接口]
B[被装饰者 普通的实现]
C[装饰者 对被装饰者进行增强]
A--实现接口-->B
A--实现接口并 组合 被装饰者-->C
- 拿人来举例
/**
* @author : mengshuo
* @Description : 接口
*/
public interface Person {
void info();
}
/**
* @author : mengshuo
* @Description : 被装饰者
*/
public class PersonA implements Person {
@Override
public void info() {
System.out.println("这是一个人!");
}
}
/**
* @author : mengshuo
* @Description : 装饰者 采用组合方式进行装饰
*/
public class PersonB implements Person {
private Person person;
public PersonB(Person person) {
this.person = person;
}
@Override
public void info() {
person.info();
System.out.println("性别:男");
}
}
使用继承实现装饰模式
- 继承实现的情况下可以省略接口
graph TD
B[被装饰者 普通的实现]
C[装饰者 对被装饰者进行增强]
B--继承被装饰者-->C
- 还是拿人举例
/**
* @author : mengshuo
* @Description : 被装饰者
*/
public class PersonA {
public void info() {
System.out.println("这是一个人!");
}
}
/**
* 使用继承方式进行装饰模式
*/
public class PersonC extends PersonA{
/**
* 如果父类无需有参构造可以省略
*/
public PersonC (){
super();
}
@Override
public void info() {
super.info();
System.out.println("性别:女");
}
}
- 测试两种模式
/**
* @author : mengshuo
* @Description :
*/
public class Test {
public static void main(String[] args) {
System.out.println("-----------------------使用组合来进行装饰模式-----------------------");
Person personB = new PersonB(new PersonA());
personB.info();
System.out.println("\n-----------------------使用继承来进行装饰模式-----------------------");
PersonC personC = new PersonC();
personC.info();
}
}
// 结果:
// -----------------------使用组合来进行装饰模式-----------------------
// 这是一个人!
// 性别:男
//
// -----------------------使用继承来进行装饰模式-----------------------
// 这是一个人!
// 性别:女
组合
也是一种设计模式 他可以用来替代继承