一、單例模式
在我們的整個游戲生命周期當中,有很多物件從始至終有且只有一個,這個唯一的實體只需要生成一次,并且直到游戲結束才需要銷毀,
單例模式一般應用于管理器類,或者是一些需要持久化存在的物件,
優點:寫起來很方便,呼叫方便,
缺點:容易形成依賴,忽略與其他設計模式的協作,
Unity的兩種單例模式
- 繼承MonoBehaviour的單例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
?
public class GameManager : MonoBehaviour
{
public static GameManager _instance;
?
void Awake()
{
_instance = this;
}
}
- 不繼承MonoBehaviour的單例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
?
public class InstanceManager
{
private static InstanceManager _instance;
public static InstanceManager Instance
{
get
{
if (_instance == null)
{
_instance = new InstanceManager();
}
return _instance;
}
}
?
}
二、工廠模式
這種型別的設計模式屬于創建型模式,它提供了一種創建物件的最佳方式,
在工廠模式中,我們在創建物件時不會對客戶端暴露創建邏輯,并且是通過使用一個共同的介面來指向新創建的物件,
應用實體: 1、您需要一輛汽車,可以直接從工廠里面提貨,而不用去管這輛汽車是怎么做出來的,以及這個汽車里面的具體實作,
2、Hibernate 換資料庫只需換方言和驅動就可以,
優點: 1、一個呼叫者想創建一個物件,只要知道其名稱就可以了,
2、擴展性高,如果想增加一個產品,只要擴展一個工廠類就可以,
3、屏蔽產品的具體實作,呼叫者只關心產品的介面,
缺點: 每次增加一個產品時,都需要增加一個具體類和物件實作工廠,使得系統中類的個數成倍增加,在一定程度上增加了系統的復雜度,同時也增加了系統具體類的依賴,這并不是什么好事,
以生產車來舉例,有吉利,紅旗,大眾三個型別,這三種都是車,那我們先寫一個車介面Car 也可以使用基類,表現效果一樣,三類人都 有Productionr 的方法
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface Car
{
void Production();
}
public class VW :Car
{
public void Production()
{
Debug.Log("生產一輛大眾");
}
}
public class GeelyAutomobile : Car
{
public void Production()
{
Debug.Log("生產一輛吉利");
}
}
public class RedFlagCar : Car
{
public void Production()
{
Debug.Log("生產一輛紅旗");
}
}
三種車的類已經創建好了,要開始進行工廠生產了,創建一個工廠類Clientele,傳入約定好的字串/Int/ 型別,即可以開始生產了,這里用一個靜態的生產方法來進行生產,所以簡單工廠模式又被稱為靜態生產模式,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Clientele
{
public static Car Clienteles(string carname)
{
switch (carname)
{
case "VW":
return new VW();
case "GeelyAutomobile":
return new GeelyAutomobile();
case "RedFlagCar":
return new RedFlagCar();
default:
break;
}
return null;
}
}
現在我們要做個測驗了,要去生產加工車了,只需要傳入想生產的型別,即可回傳你所需要的的實體
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Texter : MonoBehaviour {
void Start()
{
VW vW = (VW) Clientele.Clienteles("VW");
vW.Production();
GeelyAutomobile geelyAutomobile = (GeelyAutomobile)Clientele.Clienteles("GeelyAutomobile");
geelyAutomobile.Production();
RedFlagCar redFlagCar = (RedFlagCar)Clientele.Clienteles("RedFlagCar");
redFlagCar.Production();
}
}
將Test.cs 腳本扔到場景中,運行看看吧

后續會補充 今天就寫到這里
謝謝各位大佬捧場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/240126.html
標籤:其他
