正在阅读:用设计模式固化你的C#程序(4)用设计模式固化你的C#程序(4)

2004-02-14 09:34 出处:PConline 作者:荣耀翻译/aspcool.com 责任编辑:zwg
通过公共接口,composite模式避免了客户程序必须区分个体对象和容器对象,这在相当大的程度上促进了代码重用并简化了客户程序逻辑。 注意,Drawing类的Draw方法使用了System.Collections名字空间中的类。如欲了解类库更多知识,请参阅.NET Framework SDK的有关文档。 【译注:以下是composite模式完整示例 C#示例: using System; using System.Collections; interface Shape { void Draw(); } class Line : Shape { private double x1, y1, x2, y2; public Line(double x1, double y1, double x2, double y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public void Draw() { //从(x1, y1) 到(x2, y2)画一条线 Console.WriteLine("Drawing a line"); } } class Circle : Shape { private double x, y, r; public Circle(double x, double y, double radius) { this.x = x; this.y = y; this.r = r; } public void Draw() { //以(x, y)为圆心,r为半径画一个圆 Console.WriteLine("Drawing a circle"); } } class Drawing : Shape { private ArrayList shapes; public Drawing() { shapes = new ArrayList(); } public void Add(Shape s) { shapes.Add(s); } public void Draw() { IEnumerator enumerator = shapes.GetEnumerator(); while (enumerator.MoveNext()) ((Shape) enumerator.Current).Draw(); } } class Application { public static void Main() { Shape[] array = new Shape[3]; array[0] = new Line(0, 0, 10, 12); array[1] = new Circle(2, 3, 5.5); Drawing dwg = new Drawing(); dwg.Add(new Line(3, 4, 3, 5)); dwg.Add(new Circle(5, 6, 7.7)); array[2] = dwg; // 画出所有的图形,注意:用一致的方式来访问所有对象 for (int i = 0; i < 3; ++i) array[i].Draw(); } } /*以下是程序输出结果: Drawing a line Drawing a circle Drawing a line Drawing a circle */
键盘也能翻页,试试“← →”键

相关文章

关注我们

最新资讯离线随时看 聊天吐槽赢奖品