單例模式 Singleton Ambient Context
阿新 • • 發佈:2022-05-12
單例模式:上下文語境
using System; using System.Collections.Generic; namespace DesignParttern_Singleton_Context { public class BuildContext:IDisposable { public int Height; private static Stack<BuildContext> Stack = new Stack<BuildContext>(); public static BuildContext Current => Stack.Peek();static BuildContext() { Stack.Push(new BuildContext(0)); } public BuildContext(int i) { Height = i; Stack.Push(this); } public void Dispose() { if (Stack.Count>1) { Stack.Pop(); } } }public class Building { public List<Wall> walls = new List<Wall>(); public void Display() { walls.ForEach(a => Console.WriteLine(a)); } } public class Wall { public Point Start, End; public int Height;public Wall(Point start, Point end) { Start = start; End = end; Height = BuildContext.Current.Height; } public override string ToString() { return $"{nameof(Start)}:{Start},{nameof(End)}:{End},{nameof(Height)}:{Height},"; } } public struct Point { public int X; public int Y; public Point(int x, int y) { X = x; Y = y; } public override string ToString() { return $"x:{X},y:{Y}"; } } class Program { static void Main(string[] args) { Building building = new Building(); using (new BuildContext(3000)) { building.walls.Add(new Wall(new Point(0, 0), new Point(0, 3000))); building.walls.Add(new Wall(new Point(0, 0), new Point(4500, 0))); using (new BuildContext(3500)) { building.walls.Add(new Wall(new Point(0, 0), new Point(0, 3000))); building.walls.Add(new Wall(new Point(0, 0), new Point(4000, 0))); } building.walls.Add(new Wall(new Point(3000, 0), new Point(0, 0))); building.walls.Add(new Wall(new Point(0, 4500), new Point(0, 0))); using (new BuildContext(5000)) { building.walls.Add(new Wall(new Point(3000, 4500), new Point(4500, 3000))); } } building.Display(); } } }