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