C# 六十一、设计模式:装饰者模式

装饰模式,指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。

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

public interface IBuild
{
    void Build();
}

public class MyBuild : IBuild
{
    public void Build()
    {
        Console.WriteLine("MyBuild");
    }
}

public abstract class Decorator : IBuild
{
    private IBuild myBuild;

    public Decorator(IBuild iBuild)
    {
        myBuild = iBuild;
    }

    public virtual void Build()
    {
        myBuild.Build();
    }
}

public class SecondFloor : Decorator
{
    public SecondFloor(IBuild iBuild) : base(iBuild)
    {

    }

    public override void Build()
    {
        base.Build();
        Console.WriteLine("SecondFloor");
    }
}

public class ThreeFloor : Decorator
{
    public ThreeFloor(IBuild ibuild) : base(ibuild)
    {

    }

    public override void Build()
    {
        base.Build();
        Console.WriteLine("ThreeFloor");
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyBuild myBuild = new MyBuild();
        myBuild.Build();

        IBuild secondFloor = new SecondFloor(myBuild);
        secondFloor.Build();

        IBuild threeFloor = new ThreeFloor(myBuild);
        threeFloor.Build();

        Console.ReadKey();
    }
}

--->
MyBuild
MyBuild
SecondFloor
MyBuild
ThreeFloor

 

你可能感兴趣的:(C#)