游戏开发中的设计模式

单例模式

实例化单一对象,懒加载

typescript 复制代码
//单例模式
class GameManagerSingleton
{
    private constructor(){}
    private static instance:GameManagerSingleton;
    public static Instance()
    {
        if(!GameManagerSingleton.instance)
        {
            this.instance = new GameManagerSingleton();
        }
        return this.instance;
    }


    Init(){}

}

GameManagerSingleton.Instance().Init();

代理模式

根据不同的代理者,具体化实际方法操作

typescript 复制代码
//代理模式
interface ICall
{
    DealNum(x1:number,x2:number):number;
}

class NPC1 implements ICall
{
    DealNum(x1: number, x2: number): number {
        return x1 + x2;
    }
}

class NPC2 implements ICall
{
    DealNum(x1: number, x2: number): number {
        return x1 - x2;
    }
}

class Person
{
    public delegate : ICall;
    public DealNum(x1,x2) : number
    {
        let retNum = this.delegate.DealNum(x1,x2);
        return retNum;
    }
}

观察者模式

设置观察者后,对象的变更会告知观察者

typescript 复制代码
//观察者模式
interface IObserver
{
    nameChanged(newName);
}

class Test implements IObserver
{
  //捕捉变化
    nameChanged(newName : string) 
    {
        console.log("NewName:"+newName)
    }
}

class People
{
    private name : string;
    /**
     *
     */
    constructor() {
        this.name = ""
    }
    public get Name()
    {
       return this.name;
    }

    public set Name(value)
    {
        if(this.name != value)
        {
            this.name = value;
            //发生变化会向观察者发消息
            for(let observer of this.Observers)
            {
                observer.nameChanged(this.name);
            }
        }
        
    }
    Observers : Array<IObserver> = new Array<IObserver>();
}



let People1 = new People()
let observer1  = new Test()
//设置观察者
People1.Observers.push(observer1)
//改变对象
People1.Name = "Tom"

工厂模式

游戏中构建item群体的常用模式

typescript 复制代码
enum CarType
{
    BMW,
    Benz,
    Audi,
}


class Car 
{
   name : string;
   static CreateCar(type :  CarType)
    {
        switch(type)
        {
            case CarType.BMW:
                return new BMW();
            case CarType.Benz:
                return new Benz();
        }
    }
}

class BMW extends Car
{
    /**
     *
     */
    constructor() {
        super();
        this.name = "BMW"
    }
}
class Benz extends Car
{
    /**
     *
     */
    constructor() {
        super();
        this.name = "Benz"
    }
}

Car.CreateCar(CarType.Benz)
Car.CreateCar(CarType.BMW)
相关推荐
会员果汁1 小时前
14.设计模式-备忘录模式
设计模式·备忘录模式
xiaolyuh12311 小时前
Spring 框架 核心架构设计 深度详解
spring·设计模式·spring 设计模式
GISer_Jing1 天前
智能体工具使用、规划模式
人工智能·设计模式·prompt·aigc
GISer_Jing1 天前
AI Agent:学习与适应、模型上下文协议
人工智能·学习·设计模式·aigc
小马爱打代码1 天前
MyBatis设计模式:构建者、工厂、代理模式
设计模式·mybatis·代理模式
月明长歌1 天前
Javasynchronized 原理拆解:锁升级链路 + JVM 优化 + CAS 与 ABA 问题(完整整合版)
java·开发语言·jvm·安全·设计模式
会员果汁1 天前
12.设计模式-状态模式
设计模式·状态模式
Yu_Lijing1 天前
基于C++的《Head First设计模式》笔记——抽象工厂模式
c++·笔记·设计模式
会员果汁1 天前
13.设计模式-适配器模式
设计模式·适配器模式
GISer_Jing2 天前
AI:多智能体协作与记忆管理
人工智能·设计模式·aigc