装饰者模式的目的是给对象附加上更多功能,相对于组合方式,他不需要修改对象源码,相对于继承模式,他更加灵活。
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { class Program { /// <summary> /// 房子基类 /// </summary> public abstract class House { public abstract void Print(); } /// <summary> /// 我的房子 /// </summary> public class MyHouse : House { public override void Print() { Console.WriteLine("this is my house"); } } /// <summary> /// 房子装饰者 /// </summary> public abstract class Decorator : House { private House house; public Decorator(House house) { this.house = house; } public override void Print() { if (house != null) { house.Print(); } } } public class Window : Decorator { public Window(House house) : base(house) { } public override void Print() { base.Print(); AddWindow(); } /// <summary> /// 增加窗户 /// </summary> public void AddWindow() { Console.WriteLine("add window"); } } public class Door : Decorator { public Door(House house) : base(house) { } public override void Print() { base.Print(); AddDoor(); } /// <summary> /// 增加窗户 /// </summary> public void AddDoor() { Console.WriteLine("add door"); } } static void Main(string[] args) { House house = new MyHouse(); //给房子加窗户 Decorator window = new Window(house); window.Print(); //给房子加门 Decorator door = new Door(house); door.Print(); //同时加窗户和门 Decorator doorAndWindow = new Window(door); doorAndWindow.Print(); } } }
时间: 2024-12-27 17:40:57