日後若有Painter class也想使用IShape的strategy,只要也實做IGrapher即可。
完整程式碼如下
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 by Generic
7Release : 04/07/2007 1.0
8*/
9using System;
10
11interface IGrapher {
12 string getText();
13}
14
15interface IShape<T> {
16 void draw(T grapher);
17}
18
19class Grapher : IGrapher {
20 private IShape<Grapher> shape;
21
22 private string text;
23
24 public Grapher() { }
25 public Grapher(IShape<Grapher> shape) : this(shape, "Hello Shape!!") { }
26 public Grapher(IShape<Grapher> shape, string text) {
27 this.shape = shape;
28 this.text = text;
29 }
30
31 public void drawShape() {
32 this.shape.draw(this);
33 }
34
35 public void setShape(IShape<Grapher> shape, string text) {
36 this.text = text;
37 this.shape = shape;
38 }
39
40 public string getText () {
41 return this.text;
42 }
43}
44
45class Triangle<T> : IShape<T> where T : IGrapher {
46 public void draw(T grapher) {
47 Console.WriteLine("Draw {0:s} in Triangle", grapher.getText());
48 }
49}
50
51class Circle<T> : IShape<T> where T : IGrapher{
52 public void draw(T grapher) {
53 Console.WriteLine("Draw {0:s} in Circle", grapher.getText());
54 }
55}
56
57class Square<T> : IShape<T> where T : IGrapher {
58 public void draw(T grapher) {
59 Console.WriteLine("Draw {0:s} in Square", grapher.getText());
60 }
61}
62
63class main {
64 public static void Main() {
65 Grapher theGrapher = new Grapher(new Square<Grapher>());
66 theGrapher.drawShape();
67
68 theGrapher.setShape(new Circle<Grapher>(), "Hello C#!!");
69 theGrapher.drawShape();
70 }
71}
執行結果
Draw Hello Shape!! in Square
Draw Hello C#!! in Circle
Conclusion