C# by Delegate
1/**//*
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : DP_StrategyPattern_Delegate.cs
5Compiler : Visual Studio 2005 / C# 2.0
6Description : Demo how to implement Strategy Pattern by C# delegate
7Release : 07/08/2007 1.0
8*/
9using System;
10
11class Grapher {
12 private DrawDelegate _drawDelegate = null;
13
14 public delegate void DrawDelegate();
15
16 public Grapher() {}
17 public Grapher(DrawDelegate drawDelegate) {
18 _drawDelegate = drawDelegate;
19 }
20
21 public void drawShape() {
22 if (_drawDelegate != null)
23 _drawDelegate();
24 }
25
26 public void setShape(DrawDelegate drawDelegate) {
27 _drawDelegate = drawDelegate;
28 }
29}
30
31class Triangle {
32 public static void draw() {
33 Console.WriteLine("Draw Triangle");
34 }
35}
36
37class Circle {
38 public static void draw() {
39 Console.WriteLine("Draw Circle");
40 }
41}
42
43class Square {
44 public static void draw() {
45 Console.WriteLine("Draw Square");
46 }
47}
48
49class Program {
50 public static void Main() {
51 Grapher grapher = new Grapher(Square.draw);
52 grapher.drawShape();
53
54 grapher.setShape(Circle.draw);
55 grapher.drawShape();
56 }
57}
執行結果
Draw Square
Draw Circle
除此之外,GoF的Design Pattern也展示了使用template實做Strategy Pattern。