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

我的Design Pattern之旅[4]:使用Generic改進Strategy Pattern(OO)(3)

編輯:關於C語言

日後若有Painter class也想使用IShape的strategy,只要也實做IGrapher即可。

完整程式碼如下

1/**//*
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename  : DP_StrategyPattern3_polymorphism_this.cs
5Compiler  : Visual Studio 2005 / C# 2.0
6Description : Demo how to use Strategy Pattern with this by Generic
7Release   : 04/07/2007 1.0
8*/
9using System;
10
11interface IGrapher {
12 string getText();
13}
14
15interface IShape<T> {
16 void draw(T grapher);
17}
18
19class Grapher : IGrapher {
20 private IShape<Grapher> shape;
21
22 private string text;
23
24 public Grapher() { }
25 public Grapher(IShape<Grapher> shape) : this(shape, "Hello Shape!!") { }
26 public Grapher(IShape<Grapher> shape, string text) {
27  this.shape = shape;
28  this.text = text;
29 }
30
31 public void drawShape() {
32  this.shape.draw(this);
33 }
34
35 public void setShape(IShape<Grapher> shape, string text) {
36  this.text = text;
37  this.shape = shape;
38 }
39
40 public string getText () {
41  return this.text;
42 }
43}
44
45class Triangle<T> : IShape<T> where T : IGrapher {
46 public void draw(T grapher) {
47  Console.WriteLine("Draw {0:s} in Triangle", grapher.getText());
48 }
49}
50
51class Circle<T> : IShape<T> where T : IGrapher{
52 public void draw(T grapher) {
53  Console.WriteLine("Draw {0:s} in Circle", grapher.getText());
54 }
55}
56
57class Square<T> : IShape<T> where T : IGrapher {
58 public void draw(T grapher) {
59  Console.WriteLine("Draw {0:s} in Square", grapher.getText());
60 }
61}
62
63class main {
64 public static void Main() {
65  Grapher theGrapher = new Grapher(new Square<Grapher>());
66  theGrapher.drawShape();
67
68  theGrapher.setShape(new Circle<Grapher>(), "Hello C#!!");
69  theGrapher.drawShape();
70 }
71}

執行結果

Draw Hello Shape!! in Square

Draw Hello C#!! in Circle

Conclusion

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