《C#设计模式》==>装饰模式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPattern
{
    //装饰模式
    //动态的给一个对象增加一些额外的职责,就拓展功能而言,装饰模式提供了一种比子类更加灵活的替代方案。

    //抽象构件
    abstract class VisualComponent {
        public abstract void Display();
    }
    //具体构件
    class Window : VisualComponent
    {
        public override void Display()
        {
            Console.WriteLine("显示窗体");
        }
    }
    //具体构件
    class Textbox : VisualComponent
    {
        public override void Display()
        {
            Console.WriteLine("显示文本框");
        }
    }
    //具体构件
    class Listbox : VisualComponent
    {
        public override void Display()
        {
            Console.WriteLine("显示列表框");
        }
    }
    //构件装饰类,充当抽象装饰类
    class ComponentDecorator : VisualComponent
    {
        private VisualComponent component;//维持对抽象构建类型对象的引用******************
        //注入抽象构件类型的对象
        public ComponentDecorator(VisualComponent component) { 
            this.component = component;
        }

        public override void Display()
        {
            component.Display();
        }
    }
    //滚动条装饰类,充当具体装饰类
    class ScrollBarDecorator : ComponentDecorator {
        public ScrollBarDecorator(VisualComponent component) : base(component) { 
            
        }
        public override void Display()
        {
            this.SetScrollBar();
            base.Display();
        }
        public void SetScrollBar() {
            Console.WriteLine("为构件增加滚动条");
        }
    }
    //黑色边框装饰类,充当具体装饰类
    class BlackBorderDecorator : ComponentDecorator {
        public BlackBorderDecorator(VisualComponent component) : base(component)
        {

        }
        public override void Display()
        {
            this.SetBlackBorder();
            base.Display();
        }
        public void SetBlackBorder()
        {
            Console.WriteLine("为构件增加黑色边框");
        }
    }
    //客户端测试
    class ProgramTest {
        private void main() {
            VisualComponent component, componentSB;//使用抽象构件定义
            component = new Window();
            componentSB = new ScrollBarDecorator(component);
            component.Display();

            //输出结果
            //
            //为构件增加滚动条
            //显示窗体

            VisualComponent componentBB=new BlackBorderDecorator(componentSB);
            componentBB.Display();

            //输出结果
            //
            //为构件增加了黑色边框
            //为构件增加了滚动条
            //显示窗体



        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值