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

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

編輯:關於C語言

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++的獨門寫法。

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