首页 > 其他分享 >装饰器模式

装饰器模式

时间:2023-06-03 21:45:57浏览次数:36  
标签:Component class component 模式 装饰 Operation public Decorator

The Decorator Design Pattern attaches additional responsibilities to an object dynamically. This pattern provide a flexible alternative to subclassing for extending functionality.

装饰器模式动态的给Object添加额外的职责,这个模式为SubClassing提供灵活的扩展功能。

The Decorator Desing Pattern in C# allows us to dynamically add new functionalities to an existing object without altering or modifying its structure and this design pattern acts as a wrapper to the existing class. That mean Decorator Design Pattern dynamically changes the functionality of an object at runtime without impacting the exsiting functionality of the object. In short,this design pattern adds additional functionalities to the object by wrapping it. A decorator is an object that adds features to another object.

 

UML Class Diagram

 Component: This is an interface or abstract calss, contains members that are going to be implemented by the concrete component classes and decorator classes.

 ConcreateComponent: This is going to be a concrete class. This class simply implements the component interface.

 Decorator: This is an abstract class, This class implements the component interface or inherite abstract class and contains a reference to a component instance. This class also acts as the base class for all decorators. 

 ConcreteDecorator: This class adds additioal responsibilities to the original component by overriding the interface/abstract method.

Structure Code In C#

 /// <summary>
    /// This is the Base Component that defines operations that can be altered by decorator.
    /// </summary>
    public abstract class Component
    {
        public abstract void Operation();
    }

    /// <summary>
    /// Concrete Components provide default implementation of the operations.
    /// There might be several variations of these classes.
    /// </summary>
    public class ConcreteComponent : Component
    {
        public override void Operation()
        {
            Console.WriteLine($"ConcreteComponent.Operation()");
        }
    }
Component
    /// <summary>
    /// The base Decorator class is also inherited from the same interface as the other concrete component inherited.
    /// The Primary responsibility of this base decorator class is to define the wrapping interface for all concrete decorators.
    /// The default implementation of the wrapping code includes a filed for storing a wrapped component and we need to initialize that filed.
    /// Here, we are initializing that field using the class constructor.
    /// </summary>
    public abstract class Decorator : Component
    {
        protected Component? component;

        public void SetComponent(Component component)
        {
            this.component = component;
        }
        public override void Operation() 
        {
            component?.Operation();
        }
    }

    public class ConcreteDecoratorA : Decorator
    {
        public override void Operation()
        {
            base.Operation();
            Console.WriteLine("ConcreteDecoratorA.Operation()");
        }
    }

    public class ConcreteDecoratorB : Decorator
    {
        public override void Operation() 
        {
            base.Operation();
            AddBehavior();
            Console.WriteLine("ConcreteDecoratorB.Operation()");
        }

        void AddBehavior() 
        {
            Console.WriteLine("Add additional behavior.");
        }
    }
}
Decorator

 

When to use the Decorator Design Pattern in real-time application?

  • we want to add new functionalities to existing objects dynamically.
  • A class definition may be hidden or otherwise unavailable subclasses.

 

标签:Component,class,component,模式,装饰,Operation,public,Decorator
From: https://www.cnblogs.com/qindy/p/17410943.html

相关文章

  • 外观模式
    TheFacade designpattenprovidesaunifiedinterfacetoasetofinterfacesinasubsystem.Thispatterndefinesahigher-levelinterfacethatmakesthesubsystemeasiertouse.外观模式为子系统一组接口提供了统一的接口,这种模式定义了高级接口,便于子系统调用。......
  • 适配器模式
    TheAdpativedesignpatternconvertstheinterfaceofaclasstoanotherinterfaceclientsexpect.Thisdesignpatternletsclassesworktogetherthatcouldn'totherwisebecauseofincompatibleinterfaces.适配器模式将类的接口转换为客户期望的另外一个接口,这种......
  • 桥接模式
    TheBridgedesignpatterndecouplesanabstractionfromitsimplementationsothathetwocanvaryindependently.桥接模式将抽象和实现解耦,以便两者可以独立变化。UMLClassDiagram Abstraction:definestheabstraction'sinterface;matainsareferencetoanobj......
  • 模板方法模式
    TheTemplateMethoddesignpatterndefinestheskeletonofanalgorithminanoperation,deferingsomestepstosubclasses.Thispatternletssubclassesredefinecertainstepsofanalgorithmwihoutchangingthealgorithm'sstructure.模板方法设计模式在操作中......
  • 创建型设计模式
    TheCreationalDesignPatternareCategorizedintotwotypes. Object-CreationalPatterns:Object-CreationalPatternsdealwithobjectcreation.Here,itdeferspartofitsobjectcreationtoanotherobject.Class-CreationalPatterns:Class-CreationalPa......
  • 策略模式
    TheStrategydesignpatterndefinesafamiliyofalgorithms,encapsulateeachone,andmaketheminterchangeable.Thispatternletsthealgorithmvaryindependentlyfromclientthatuseit.策略模式定义一系列算法,封装它,使他们可以互换,这种设计模式使算法独立于客......
  • 3月25日邓老师设计模式面试资料02
    Spring面试专题1.Spring应该很熟悉吧?来介绍下你的Spring的理解  有些同学可能会抢答,不熟悉!!!  好了,不开玩笑,面对这个问题我们应该怎么来回答呢?我们给大家梳理这个几个维度来回答1.1Spring的发展历程  先介绍Spring是怎么来的,发展中有哪些核心的节点,当前的最新版本是......
  • 大话设计模式之单例,策略,简单工厂
    基于实际面试题实现importjava.util.HashMap;importjava.util.Map;importjava.util.Random;/***用java设计一个机房环境监测系统的代码框架,机房有多种传感器,可以实时检测机房的温度、湿度、噪音等数据,*并把数据实时发送到监控中心,其中某项数据超过不健康阈值立即上......
  • 树莓派如果通过 raspi-config 关闭桌面模式 All In One
    树莓派如果通过raspi-config关闭桌面模式AllInOne树莓派设置启动模式:切换桌面模式和命令行模式DesktopCommandLineGUIvsCLI图形化界面vs命令行$sudoraspi-config$sudovim/boot/config.txt$sudoreboot$sudoshutdwon-hnowautologinde......
  • 大白话讲解数据库的三级模式(所谓的内外模式在生活中到底是什么东西?)
    具象化理解数据库的三级模式形象一点来说,把数据看做货物,数据库是仓库,模式就是表格。你有一个仓库,仓库里成千上万的货物,随便你怎么堆,你堆个正方体,堆个圆柱体,甚至随便乱堆都行,你怎么堆的叫内模式。完事你写了一张表,表上对全部货物按某个标准分类,而且标清了啥货物在哪(这个是模式内......