1. 程式人生 > 實用技巧 >C# 單例簡單例項

C# 單例簡單例項

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace SingletonPatternTest
 9 {
10     public class ReadWordService
11     {
12 #region
13         private static ReadWordService _instance;
14 15 private ReadWordService() { } 16 17 public static ReadWordService Instance() 18 { 19 if (_instance == null) 20 { 21 _instance = new ReadWordService(); 22 } 23 return _instance; 24 } 25 #endregion 26
27 public void GetReadWord() 28 { 29 while (true) 30 { 31 var words = Console.ReadLine(); 32 33 if (!string.IsNullOrEmpty(words) && words.Length > 10) 34 { 35 Console.WriteLine("你要輸出的內容是
" + words); 36 break; 37 } 38 else 39 { 40 Console.WriteLine("不符合條件的輸入:" + words); 41 } 42 } 43 } 44 } 45 }

控制檯實現部分

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace SingletonPatternTest
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             // SingletonService.Instance().HellodWord();
14             ReadWordService.Instance().GetReadWord();
15             Console.ReadKey();
16 
17         }
18     }
19 }

顯示結果