装饰器模式
说明
装饰器模式(Decorator Pattern)属于结构型模式,也叫包装模式(Wrapper Pattern),是指在不改变原有对象的基础之上,将功能附加到对象上,提供比继承更有弹性的替换方案(扩展原有对象的功能)。
在实际开发中,一个类的可能会因业务场景不同需要一些功能,而这些功能并不是这个类必须的,如果将这些功能直接定义在类中或者使用继承的方式实现都不太适合。这时就需要装饰器模式,它将一个类的核心功能与装饰功能解耦分离,在需要的时候在动态的附加上。
技多不压身,某些技能平时不会用,但是某些场景却必须要用。
结构
装饰器模式的主要角色如下:
抽象组件(Component):可以是一个类或者接口,定义了被装饰对象的功能;
具体组件(ConcreteComponent):实现/继承Component的具体对象,也就是被装饰的对象;
抽象装饰器(Decorator):具体装饰器的抽象类,需要包含Component的引用,并且继承或实现Component。该类不是必须的,如果具体的装饰器有多个,则需要该类;
具体装饰器(ConcreteDecorator):Decorator的具体实现,实现了具体的装饰功能。
代码案例
/**
* @program: decorator
* @description: 技能接口
* @author: wxw
* @create: 2024-03-09 09:48
**/
public interface ISkill {
/**
* 展示技能
*/
void showSkill();
}
/**
* @program: decorator
* @description: 人类
* @author: wxw
* @create: 2024-03-09 09:50
**/
public class Human implements ISkill {
private String name;
private Integer age;
public Human(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public void showSkill() {
System.out.print(name + "的技能:");
}
}
/**
* @program: decorator
* @description: 技能装饰器
* @author: wxw
* @create: 2024-03-09 09:53
**/
public abstract class SkillDecorator implements ISkill{
protected ISkill human;
public SkillDecorator(ISkill human) {
this.human = human;
}
}
/**
* @program: decorator
* @description: 健身技能装饰器
* @author: wxw
* @create: 2024-03-09 09:55
**/
public class FitnessSkillDecorator extends SkillDecorator{
public FitnessSkillDecorator(ISkill human) {
super(human);
}
@Override
public void showSkill() {
human.showSkill();
System.out.print("健身、");
}
}
/**
* @program: decorator
* @description: 唱歌技能装饰器
* @author: wxw
* @create: 2024-03-09 09:55
**/
public class SingSkillDecorator extends SkillDecorator{
public SingSkillDecorator(ISkill human) {
super(human);
}
@Override
public void showSkill() {
human.showSkill();
System.out.print("唱歌、");
}
}
/**
* @program: decorator
* @description: 编程技能装饰器
* @author: wxw
* @create: 2024-03-09 09:55
**/
public class ProgrammingSkillDecorator extends SkillDecorator{
public ProgrammingSkillDecorator(ISkill human) {
super(human);
}
@Override
public void showSkill() {
human.showSkill();
System.out.print("编程、");
}
}
public class Test {
public static void main(String[] args) {
ISkill human = new Human("张三", 20);
ISkill zhansanSkill = new ProgrammingSkillDecorator(new SingSkillDecorator(new FitnessSkillDecorator(human)));
zhansanSkill.showSkill();
}
}
输出结果:
张三的技能:健身、唱歌、编程、