软件设计模式-装饰者模式
装饰模式
应用场景:
最基础用法:
当需要对类A的对象添加一些自定义不同的方法时,直接在类A中添加方法不太好!那么需要一个类B继承类A,类B里面增加一个类A的对象作为自己的成员并自定义一个方法Bfunc,再重载类A中的某个方法func,在该方法里面调用自己的Bfunc。
高级用法:假设要对男英雄和女英雄进行装饰(技能加点),那么他们应该都实现同一个接口(英雄),而装饰者也有不同类型(学习qwer技能)所以也应该实现同一个总装饰接口或者抽象类(学习技能)但由于装饰模式的含义是在原有基础上添加新方法,所以总装饰接口应当保留英雄的基本属性(即应当实现接口:英雄),具体看代码
// 组件接口(英雄)
public interface Component {
void operation();
}
// 具体组件类(男英雄或女英雄)
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("ConcreteComponent: 男英雄的基本操作");
}
}
// 装饰抽象类(学习技能)
public abstract class Decorator implements Component {
protected Component component; # 总装饰接口应当保留英雄的基本属性
public Decorator(Component component) {
this.component = component;
}
@Override # 实现了接口就要重写该接口里的函数
public void operation() {
component.operation(); // 调用原始组件的操作
}
}
// 具体装饰类A,增加额外功能(学习q技能)
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void operation() {
super.operation(); // 执行原始组件的操作
addedBehavior(); // 增强操作
}
private void addedBehavior() {
System.out.println("ConcreteDecoratorA: 学习q技能");
}
}
本文作者:torrentgz
本文链接:https://www.cnblogs.com/torrentgz/p/18425393
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步