In this paper, a simple example to illustrate the implementation of the C # Strategy model, shared for everyone to reference. The implementation method is as follows:
In general, when there are multiple implementations of an action, you might consider using a policy mode when you need to choose a method to perform the action according to different circumstances.
Abstract the action into an interface, such as playing the ball into an interface. The code is as follows:
public interface iball{ void Play ();
It is possible to play football, basketball, volleyball, etc., to abstract these balls into a class to implement the interface. The following are the differences:
public class football:iball{public void Play () { Console.WriteLine ("I like Football");} } public class basketball:iball{public void Play () { Console.WriteLine ("I like Basketball");} } public class volleyball:iball{public void Play () { Console.WriteLine ("I like Volleyball");} }
There is also a class that is dedicated to choosing which balls to use and to execute the interface method:
public class sportsman{ private IBall ball; public void Sethobby (IBall myball) {ball = Myball; } public void Startplay () {ball . Play (); }}
The client needs to make a choice for the user to instantiate a specific class based on different choices:
Class program{ static void Main (string[] args) { IBall ball = null; Sportsman man = new Sportsman (); while (true) { Console.WriteLine ("Select the ball item you like (1= football, 2 = basketball, 3 = volleyball)"); string input = Console.ReadLine (); switch (input) {case ' 1 ': ball = new Football (); break; Case "2": Ball = new Basketball (); break; Case "3": Ball = new Volleyball (); break; } Man. Sethobby (ball); Man. Startplay ();}}}
The results of the program run are as follows:
I hope this article is helpful to everyone's C # programming.
In addition to the Declaration,
Running GuestArticles are original, reproduced please link to the form of the address of this article
C # Policy mode (strategy pattern) Example Tutorial
This address: http://www.paobuke.com/develop/c-develop/pbk23519.html
Related content C # set custom file icon implementation double-click Start (Modify registry) C # Call stored procedure in detail (with return value, parameter input and output, etc.) 12306 the code of Practice for the implementation of C # implement CAPTCHA code program C # Custom Control Add a right-click menu
C # read Excel and convert it to XML method C # implement JSON to Unicode C # implement Shuffle game instance method of converting English letters to uppercase or lowercase in C #
C # Policy mode (strategy pattern) Example Tutorial