C#设计模式-结构型模式-3.装饰者模式
Posted mr.chenyuelin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#设计模式-结构型模式-3.装饰者模式相关的知识,希望对你有一定的参考价值。
装饰者顾名思义就是对一个类添加一些额外的装饰(功能)
结构图:
具体装饰类concreteDecorate就是我们要添加的功能
例子,比如我们盖了一个房子,我们想要装修房子,更安全或者更好看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 装饰者模式
//房子抽象接口,component类型
public abstract class House
//装修方法
public abstract void Renovation();
//装饰接口,Decorator
public abstract class DecorationStrategy:House
protected House house;
protected DecorationStrategy(House house)
this.house = house;
//装修方法
public override void Renovation()
if(this.house!=null)
this.house.Renovation();
//具体装修的房子,concreteComponent
public sealed class InitFamilyHouse : House
public override void Renovation()
Console.WriteLine("装修家里的房子");
//具体安全功能,concreteDecorateA
public sealed class HouseSecurityDecorator:DecorationStrategy
public HouseSecurityDecorator(House house) : base(house)
public override void Renovation()
base.Renovation();
Console.WriteLine("增加安全系统");
//具体保暖功能,concreteDecorateB
public sealed class KeepWarmDecorator:DecorationStrategy
public KeepWarmDecorator(House house) : base(house)
public override void Renovation()
base.Renovation();
Console.WriteLine("增加保暖系统");
class Program
static void Main(string[] args)
House familyHouse = new InitFamilyHouse();
DecorationStrategy securityHouse = new HouseSecurityDecorator(familyHouse);
securityHouse.Renovation();
DecorationStrategy keepWarmHose = new KeepWarmDecorator(familyHouse);
keepWarmHose.Renovation();
以上是关于C#设计模式-结构型模式-3.装饰者模式的主要内容,如果未能解决你的问题,请参考以下文章