1. 程式人生 > >單例模式之二

單例模式之二

單例模式分為兩種一種是繼承mono的一種是不繼承mono的
不繼承mono的 常用於資料的管理
不繼承mono:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


namespace Sington
{
    public class SingleTonTest /*: MonoBehaviour */
    {
        //不繼承mono的單利  常用於資料的管理類

        public string name = "VR-1";

        //儲存  當前類唯一例項的物件
private static SingleTonTest instance; //需要一個位置對當前物件進行例項化 而且是唯一的例項化 //public static SingleTonTest GetInstance() //{ // if (instance == null) // { // //當前類沒有例項化 // instance = new SingleTonTest(); // } // return instance;
//} //屬性訪問器形式 public static SingleTonTest Instance { get { if (instance == null) { instance = new SingleTonTest(); } return instance; } } public void
Print() { System.Console.WriteLine("列印方法"); } /// <summary> /// 當前需要單例的類的構造私有化 /// </summary> private SingleTonTest() { } } public class Test { public void Main() { //1.方法形式獲取單例 //SingleTonTest.GetInstance(); //2.屬性訪問器形式獲取單例 SingleTonTest a = SingleTonTest.Instance; string name = a.name; a.Print(); } } }

繼承mono的

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SingleTonMono : MonoBehaviour {
    //繼承mono的單利
    //在遊戲中  負責統籌管理的類  需要調到mono中的方法  Load<Sprite>
    public int playerGold=100;
    private static SingleTonMono instance;   //靜態的可以用類去呼叫
    //比如在別腳本中用 singleton.ins  來呼叫下面寫的方法Instance

    public static SingleTonMono Instance
    {
        get {
            return instance;
        }
    }

    void Awake()
    {
        instance = this;
    }

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}