程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 我的Design Pattern之旅[1]:Strategy Pattern (OO)(5)

我的Design Pattern之旅[1]:Strategy Pattern (OO)(5)

編輯:關於C語言

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。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved