敏捷软件开发 原则、模式与实践 第9章的例子程序(C#版)
代码中为每个形状指定了序号,如果再来一颗子弹,让你要按类型打印的同时,还要按照序号从小到大排列怎么做呢?
1 using System; 2 using System.Collections.Generic; 3 4 namespace DesignPattern 5 { 6 class Program 7 { 8 public static readonly string[] OrderStrings = 9 { 10 nameof(Square), 11 nameof(Triangle), 12 nameof(Circle), 13 null 14 }; 15 16 static void Main(string[] args) 17 { 18 // 产生若干个随机图形 19 Random random = new Random(); 20 var shapes = new List<Shape>(); 21 for (int i = 0; i < 100; i++) 22 { 23 var value = random.Next(0, 15); 24 if (value < 5) 25 { 26 shapes.Add(new Square() { Index = i }); 27 } 28 else if (value < 10) 29 { 30 shapes.Add(new Triangle() { Index = i }); 31 } 32 else 33 { 34 shapes.Add(new Circle() { Index = i }); 35 } 36 } 37 38 shapes.Sort( 39 (left, right) => 40 { 41 if (left < right) 42 { 43 return -1; 44 } 45 46 if (left > right) 47 { 48 return 1; 49 } 50 51 return 0; 52 }); 53 shapes.ForEach(shape => shape.Draw()); 54 55 Console.ReadLine(); 56 } 57 } 58 59 public class Shape 60 { 61 public int Index { get; set; } 62 63 public virtual void Draw() 64 { 65 Console.WriteLine($"画了Shape基类{Index}"); 66 } 67 68 public static bool operator <(Shape left, Shape right) 69 { 70 var leftTypeName = left.GetType().Name; 71 var leftIndex = -1; 72 var rightTypeName = right.GetType().Name; 73 var rightIndex = -1; 74 for (int i = 0; i < Program.OrderStrings.Length; i++) 75 { 76 if (leftTypeName == Program.OrderStrings[i]) 77 { 78 leftIndex = i; 79 } 80 81 if (rightTypeName == Program.OrderStrings[i]) 82 { 83 rightIndex = i; 84 } 85 } 86 return leftIndex < rightIndex; 87 } 88 89 public static bool operator >(Shape left, Shape right) 90 { 91 return !(left < right); 92 } 93 } 94 95 public class Square:Shape 96 { 97 public override void Draw() 98 { 99 Console.WriteLine($"画了正方形{Index}"); 100 } 101 } 102 103 public class Circle : Shape 104 { 105 public override void Draw() 106 { 107 Console.WriteLine($"画了圆{Index}"); 108 } 109 } 110 111 public class Triangle : Shape 112 { 113 public override void Draw() 114 { 115 Console.WriteLine($"画了三角形{Index}"); 116 } 117 } 118 }