Abstract
在(原创) 我的Design Pattern之旅:使用template改进Strategy Pattern (OO) (Design Pattern) (C/C++) (template)中,使用了C++的template改进strategy pattern,本文使用C#的generic改进strategy pattern。
Introduction
C# 2.0加入了generic对泛型的支援,所以想将原来C++的template程式一行一行的改成C# generic。
在strategy pattern中,通常为了让strategy能完全存取物件的public method/property,我们会利用传this将整个物件传给strategy
public void drawShape() {
this.shape.draw(this);
}
为了达成此需求,我们的interface须如此定义
interface IShape {
void draw(Grapher grapher);
}
完整的程式码如下
1/**//*
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : DP_StrategyPattern3_polymorphism_this.cs
5Compiler : Visual Studio 2005 / C# 2.0
6Description : Demo how to use Strategy Pattern with this
7Release : 04/07/2007 1.0
8*/
9using System;
10
11interface IShape {
12 void draw(Grapher grapher);
13}
14
15class Grapher {
16 private IShape shape;
17 private string text;
18
19 public Grapher() { }
20 public Grapher(IShape shape) : this(shape, "Hello Shape!!") { }
21 public Grapher(IShape shape, string text) {
22 this.shape = shape;
23 this.text = text;
24 }
25
26 public void drawShape() {
27 this.shape.draw(this);
28 }
29
30 public void setShape(IShape shape, string text) {
31 this.text = text;
32 this.shape = shape;
33 }
34
35 public string getText () {
36 return this.text;
37 }
38}
39
40
41class Triangle : IShape {
42 public void draw(Grapher grapher) {
43 Console.WriteLine("Draw {0:s} in Triangle", grapher.getText());
44 }
45}
46
47class Circle: IShape {
48 public void draw(Grapher grapher) {
49 Console.WriteLine("Draw {0:s} in Circle", grapher.getText());
50 }
51}
52
53class Square : IShape {
54 public void draw(Grapher grapher) {
55 Console.WriteLine("Draw {0:s} in Square", grapher.getText());
56 }
57}
58
59class main {
60 public static void Main() {
61 Grapher theGrapher = new Grapher(new Square());
62 theGrapher.drawShape();
63
64 theGrapher.setShape(new Circle(), "Hello C#!!");
65 theGrapher.drawShape();
66 }
67}
执行结果
Draw Hello Shape!! in Square
Draw Hello C#!! in Circle