C# by Generics
1/**//*
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : DP_StrategyPattern_Generics.cs
5Compiler : Visual Studio 2005 / C# 2.0
6Description : Demo how to implement Strategy Pattern by C# Generics
7Release : 07/08/2007 1.0
8*/
9using System;
10
11interface IDrawStrategy {
12 void draw();
13}
14
15class Grapher<T> where T : class, IDrawStrategy, new() {
16 private T _drawStrategy = default(T);
17
18 public Grapher() {
19 _drawStrategy = new T();
20 }
21
22 public void drawShape() {
23 if (_drawStrategy != null)
24 _drawStrategy.draw();
25 }
26
27 public void setShape(T drawStrategy) {
28 _drawStrategy = drawStrategy;
29 }
30}
31
32class Triangle : IDrawStrategy {
33 public void draw() {
34 Console.WriteLine("Draw Triangle");
35 }
36}
37
38class Circle : IDrawStrategy {
39 public void draw() {
40 Console.WriteLine("Draw Circle");
41 }
42}
43
44class Square : IDrawStrategy {
45 public void draw() {
46 Console.WriteLine("Draw Square");
47 }
48}
49
50class Program {
51 public static void Main() {
52 Grapher<Square> grapher = new Grapher<Square>();
53 grapher.drawShape();
54
55 Grapher<Circle> grapher2 = new Grapher<Circle>();
56 grapher2.drawShape();
57 }
58}
執行結果
Draw Square
Draw Circle
Remark
strategy和template method目的相同,皆對『新需求』的不同演算法提供『擴充』的機制,但手法卻不同,strategy采用object的方式,利用delegation改變演算法,而template method則采用class的繼承方式來改變演算法,也因為strategy采用object方式,所以有run-time改變的可能,但template method采class手法,所以無法run-time改變。
GoF的原文如下
Template methods use inheritance to vary part of an algorithm. StrategIEs use delegation to vary the entire algorithm.
Known Use
1.eclipse的plugin,可以在不修改eclipse原始碼下,外掛plugin變更eclipse所提供的功能。