单例模式+游戏开发中的设计模式——单例模式

01、设计模式:这是最全面 & 详细的 单例模式(Singleton)分析指南

https://blog.csdn.net/carson_ho/article/details/52223097

02、单例模式的优缺点

https://blog.csdn.net/iblade/article/details/51107308

何为单例模式

单例模式(singleton):保证只有一个类仅有一个实例,并提供一个访问他的全局访问点。

单例模式有三个要点:一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。 
单例模式是结构最简单的设计模式一,在它的核心结构中只包含一个被称为单例类的特殊类。

应用场合

在以下情况下可以考虑使用单例模式: 
- (1) 系统只需要一个实例对象,如系统要求提供一个唯一的序列号生成器或资源管理器,或者需要考虑资源消耗太大而只允许创建一个对象。 
- (2) 客户调用类的单个实例只允许使用一个公共访问点,除了该公共访问点,不能通过其他途径访问该实例。

案例+代码实现

 //单例模式--静态初始化(饿汉式),,,此外还有多线程情况中的双重锁定(饱汗式) 也可以实现相同功能
    //01创建静态的私有变量,并实例化(在第一次引用类的任何成员时创建实例)
    private static GameFacade _instance = new GameFacade();

    //02私有化构造函数(不能再外部实例化,即不能new)
    private GameFacade() { }

    //03创建全局唯一访问点
    public static GameFacade Instance { get { return _instance; } }

案例:

将Facade类做成单例模式

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class GameFacade  {

    //创建游戏子系统管理的总类Facade(外观模式)

    //单例模式--静态初始化,,,此外还有多线程情况中的双重锁定 也可以实现相同功能
    //01创建静态的私有变量,并实例化(在第一次引用类的任何成员时创建实例)
    private static GameFacade _instance = new GameFacade();


    private bool mIsGameOver = false;//辅助状态管理,添加游戏是否结束,判断何时切换场景

    //单例模式
    //03创建全局唯一访问点
    public static GameFacade Instance { get { return _instance; } }


    public bool isGameOver {get { return mIsGameOver; }}

    //单例模式
    //02私有化构造函数(不能再外部实例化,即不能new)
    private GameFacade() { }



	public void Init () //即MethodOne
    {
        //具体的A\B\C\D等子类
	
	}


    public void Update()//即MethodTwo
    {
        //具体的A\B\C\D等子类
	}

    public void Release() //即MethodThree
    {
        //具体的A\B\C\D等子类
    }
}


使用

        例:GameFacade.Instance .Init();

using System;
using System.Collections.Generic;
using System.Text;

public  class AttackState:ISceneState
{
    public AttackState(SceneStateControl controller): base("03AttackScene", controller)
    { 
        
    }
    
    //private GameFacade mFacade;//做成了单例模式
    //创建一个类,管理
    //兵营、关卡、角色管理、行动力、成就等子系统系统
    //由于Facade类的作用,AttackState可以不用知道具体子类的存在
    //使用Facade外观模式,使AttackState很简洁,只处理与自身状态有关的


    public override void StateStart()
    {
        //mFacade.Init();
        GameFacade.Instance .Init();//使用FacademethodOne
    }

    public override void StateEnd()
    {
        //mFacade.Release();//使用FacademethodTwo
        GameFacade.Instance.Release();
    }

    public override void StateUpdate()
    {
        if(GameFacade.Instance.isGameOver){
            mControler.SetState(new MainState(mControler));
        }
        GameFacade.Instance.Update();//使用FacademethodThree
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35422344/article/details/86303742