裝飾器模式 動態組合裝飾
阿新 • • 發佈:2022-05-18
DesignPartten_Decoration_Dynamic_Composition
先定義個一個形狀的介面,可以轉換為字串
interface IShape { string AsString(); }
新增各種形狀
class Circel:IShape { float ridus; public Circel(float ridus) { this.ridus = ridus; } public string AsString() {return $"Circle Ridus:{ridus}"; } public void Resize(float size) { ridus *= size; } } class Square :IShape { float Side; public Square(float side) { Side = side; } public string AsString() {return $"Square Side: {Side}" ; } }
開始裝飾:
class ColorShape : IShape { IShape shape; string color; public ColorShape(IShape shape, string color) { this.shape = shape; this.color = color; } public string AsString() {return $"{shape.AsString()} Color :{color}"; } } class Transparent:IShape { IShape shape; float percentage; public Transparent(IShape shape, float _percentage) { this.shape = shape; this.percentage = _percentage; } public string AsString() { return $"{shape.AsString()} Transparent:{percentage*100.0}%"; } } class Program { static void Main(string[] args) { Square sq = new Square(1.23f); Console.WriteLine(sq.AsString()); ColorShape colorShape = new ColorShape(sq, "Black"); Console.WriteLine(colorShape.AsString()); Transparent transparent = new Transparent(colorShape, 0.5f); Console.WriteLine(transparent.AsString()); } }
執行時呼叫