Abstract
In (original) My Design journey: using template to improve strategy pattern (OO) (c + +) (template), use C + + Template improved strategy pattern, this article uses C # 's generic to improve strategy pattern.
Introduction
C # 2.0 joined the generic support for generics, so you want to change the original C + + template program line to C # generic.
In strategy pattern, in order for strategy to fully access the public method/property of an object, we use this to pass the entire object to strategy
public void drawShape() {
this.shape.draw(this);
}
In order to achieve this demand, our interface must be so defined
interface IShape {
void draw(Grapher grapher);
}
The complete code is as follows
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 This
7release:04/07/2007 1.0
8*/
9using System;
Ten
11interface ishape {
void Draw (Grapher Grapher);
13}
15class Grapher {
Private ishape shape;
private string Text
a
public Grapher () {}< br> public Grapher (ishape shape): This (Shape, "Hello shape!!") {}
Public Grapher (ishape shape, string text) {
This.shape = shape;
This.text = text;
on}
is public void Drawshape () {
-This.shape.draw (this),
"
"
public void Setshape (IShape shap E, string text) {
This.text = text;
This.shape = shape,
}
-
-public string GetText () { br> return this.text;
37}
38}
All
41class TriangLe:ishape {
Draw (Grapher Grapher) {
to Console.WriteLine ("Draw {0:s} in triangle", Grapher.gette XT ());
44}
45}
47class circle:ishape {
public void Draw (Grapher Grapher) {
-Console.WriteLine ("Draw {0:s} in C Ircle ", Grapher.gettext ());
50}
51}
53class square:ishape {
' public void Draw (Grapher Grapher) {
-Console.WriteLine ("Draw {0:s} in Square ", Grapher.gettext ());
56}
57}
59class Main {
# public static void main () {
Grapher thegrapher = new Grapher (new Square ());
Thegrapher.drawshape ();
Thegrapher.setshape (New Circle (), "Hello c#!!");
Thegrapher.drawshape ();
66}
I}
Execution results
Draw Hello Shape!! in Square
Draw Hello C#!! in Circle