1. 程式人生 > 實用技巧 >設計模式之單例模式(控制檯方法)

設計模式之單例模式(控制檯方法)

介紹

單例模式是軟體工程中最著名的模式之一。從本質上講,單例是一個只允許建立自身的單個例項的類,並且通常可以簡單地訪問該例項。最常見的是,單例不允許在建立例項時指定任何引數——否則對例項的第二個請求但具有不同的引數可能會有問題!(如果對於具有相同引數的所有請求都應訪問相同的例項,則工廠模式更合適。)本文僅處理不需要引數的情況。通常,單例的要求是它們是懶惰地建立的——即直到第一次需要時才建立例項。 具體介紹請看另一個博主的部落格,轉載於 https://www.cnblogs.com/leolion/p/10241822.html

我在這裡介紹的是餓漢模式,建立兩個類,一個是普通的類,一個是單例類

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Day12
 8 {
 9     class Student1
10     {
11         //第一步:建構函式私有化,這樣就不能用new進行例項
12         private Student1() { }
13         //第二步:自行建立一個例項,採用static代表一個例項
14 private static Student1 student1 = new Student1();//餓漢模式 15 //第三步:提供外界能訪問的方法 16 public static Student1 Getstudent1() 17 { 18 return student1; 19 } 20 public string Name { get; set; } 21 public void Show() 22 { 23 Console.WriteLine("
HELLO!" + Name); 24 } 25 } 26 }
Student1.cs
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Day12
 8 {
 9     public class Student
10     {
11         public string Name { get; set; }
12         public void Show()
13         {
14             Console.WriteLine("HELLO!"+Name);
15         }
16     }
17 }
Student1.c

然後在控制檯上輸出,呼叫要進行輸出的方法和要賦值的欄位名稱

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Day12
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             //Student st = new Student();
14             //st.Name = "王鵬澤";
15             //st.Show();
16             Student1 st = Student1.Getstudent1();
17             st.Name = "jack";
18             st.Show();
19             Student1 st1 = Student1.Getstudent1();
20             st1.Show();
21             Console.ReadLine();
22         }
23     }
24 }
Program.cs