装饰模式

装饰模式:动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。
 
Component定义一个对象接口,可以给这些对象动态的添加职责。
ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。
Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在。
ConcreteDecoratorA和ConcreteDecoratorB是具体装饰对象,起到给Component添加职责的功能。
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
abstract class Component{
     public abstract void Operation();
}
class ConcreteComponent extend Component{
     public Operation(){
         console.log(“具体对象操作”);
     }
}
abstract class Decorator extend Component{
     protected Component component;
     public setComponent(Component component){
          this.component = component;
     }
     public Operation(){
          if(this.component != null){
               component.Operation();
          }
     }
}
class ConcreteDecoratorA extend Decorator{
     private string addedState;
     public Operation(){
          super.Operation();
          addedState = "new State";
          console.log("具体装饰对象A操作");
     }
}
class ConcreteDecoratorB extend Decorator{
     public Operation(){
          super.Operation();
          addedBehavior();
          console.log("装饰对象B的操作");
     }
     private addedBehavior(){}
}
class Main{
     ConcreteComponent c = new ConcreteComponent();
     ConcreteDecoratorA d1 = new ConcreteDecoratorA();
     ConcreteDecoratorB d2 = new ConcreteDecoratorB();
 
     d1.setComponent(c);
     d2.setComponent(d1);
     d2.Operation();
}

  

 该模式利用setComponent来对对象进行包装,每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中。
 
 
总结:装饰模式是为已有功能动态的添加更多功能的方式。
当系统需要新功能的时候,是向旧的类添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为。
如果我们在主类中加入了新的字段,新的方法和新的逻辑,从而增加了主类复杂度,而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要。而装饰模式却提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所需要的装饰对象,因为,当需要执行特殊行为时,特护代码就可以在运行时根据需要有选择的、按顺序的使用装饰功能包装对象。
 
 
 
 
 
 
 
posted @   樱良orz  阅读(364)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示