This article is a simple example of the C # object is a null mode (Null object pattern), shared for everyone to reference. The implementation method is as follows:
The so-called "object is null mode", is to ask the developer to consider the object is null, and design the response in this case.
With the front "
"In the example of the article, in our client program only consider the user input of the case, if the user input other numbers, such as 4, there is no corresponding IBall interface implementation class instance generated, and will report the following error:
To cope with this situation, we specifically designed a class that produces instances of this class when the user enters a number above the above-mentioned. This class also implements the IBall interface.
public class others:iball{public void Play () { Console.WriteLine ("The ball item you selected does not currently exist ~ ~");} }
In the client program, modify to:
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; Default: Ball = new Others (); break; } Man. Sethobby (ball); Man. Startplay ();}}}
Above, in the default section of the Swich statement, when the user enters a number other than A/d, a class instance that implements the IBall interface and is specifically handling null is created.
It is believed that the example mentioned in this paper has some reference value to the study of C # program design.
In addition to the Declaration,
Running GuestArticles are original, reproduced please link to the form of the address of this article
Example tutorial for C # object NULL mode (Null object pattern)
This address: http://www.paobuke.com/develop/c-develop/pbk23518.html
Related Content C # sendmail send mail function Implementation C # Implementation Google Translate API sample code STACKEXCHANGE.REDIS generic encapsulation class share WPF dragging DataGrid scroll bar when confusing content resolution
An analysis of the efficiency of StringBuilder class in C # and its comparison with string the linkage operation of C # ComboBox (three-tier architecture) C # Operation FTP class full Instance C # determine how much a day, year has elapsed
Example tutorial for C # object NULL mode (Null object pattern)