装饰模式
定义:动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。
//对象接口 public abstract class Component { public abstract void operation(); }
ConcreteComponent:定义一个具体的对象,也可以给这个对象添加一些职责
public class ConcreteComponent extends Component { @Override public void operation() { System.out.println("具体对象的操作"); } }
Decorator:装饰抽象类,继承了Component,从外类扩展Component的功能,但对于Componnet来说,不需要知道Decorator的存在
public abstract class Decorator extends Component { protected Component component; public void setComponent(Component component){ this.component = component; } @Override public void operation(){ if(component!=null){ component.operation(); } } }
ConcreteDecoratorA:具体的装饰对象
public class ConcreteDecoratorA extends Decorator { public void operation(){ super.operation(); eat(); } private void eat(){ System.out.println("装饰新增方法"); } }
public static void main(String[] args) { ConcreteComponent c = new ConcreteComponent(); ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA(); concreteDecoratorA.setComponent(c); concreteDecoratorA.operation(); }
总结:装饰模式是利用setComponent来对对象进行包装,这样可以让装饰对象的实现和如何使用进行分离。
使用场景:当系统需要增加新功能的时候,是向旧的类中添加了新的代码,增加了新的方法和新的逻辑,从而增加了主类的复杂度。而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要,装饰模式提供了一个非常好的解决方案,把每个要装饰的功能放在单独的类中,并让这个类包装他所需要装饰的对象。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix