C# by Interface
1/**//*
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : DP_StrategyPattern_Classic.cs
5Compiler : Visual Studio 2005 / C# 2.0
6Description : Demo how to implement Strategy Pattern by C#
7Release : 07/08/2007 1.0
8*/
9using System;
10
11interface IDrawStrategy {
12 void draw();
13}
14
15class Grapher {
16 private IDrawStrategy _drawStrategy = null;
17
18 public Grapher() {}
19 public Grapher(IDrawStrategy drawStrategy) {
20 _drawStrategy = drawStrategy;
21 }
22
23 public void drawShape() {
24 if (_drawStrategy != null)
25 _drawStrategy.draw();
26 }
27
28 public void setShape(IDrawStrategy drawStrategy) {
29 _drawStrategy = drawStrategy;
30 }
31}
32
33class Triangle : IDrawStrategy {
34 public void draw() {
35 Console.WriteLine("Draw Triangle");
36 }
37}
38
39class Circle : IDrawStrategy {
40 public void draw() {
41 Console.WriteLine("Draw Circle");
42 }
43}
44
45class Square : IDrawStrategy {
46 public void draw() {
47 Console.WriteLine("Draw Square");
48 }
49}
50
51class Program {
52 public static void Main() {
53 Grapher grapher = new Grapher(new Square());
54 grapher.drawShape();
55
56 grapher.setShape(new Circle());
57 grapher.drawShape();
58 }
59}
執行結果
Draw Square
Draw Circle
使用interface是最正規的OOP寫法,另外Effective C++的item 35也使用了function pointer來實做strategy pattern,function pointer是C/C++的獨門寫法。