文章

享元模式

享元模式是一种结构型模式,它通过共享技术实现大量细粒度对象的复用,从而减少系统资源的消耗,提高系统性能。在游戏开发中,享元模式常用于实现粒子系统、地形系统等。

例如,在一个射击游戏中,需要大量的子弹来实现游戏效果,可以使用享元模式来实现子弹池:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class Bullet {
    private Vector3 position;
    private Vector3 direction;
    private float speed;

    public Bullet(Vector3 position, Vector3 direction, float speed) {
        this.position = position;
        this.direction = direction;
        this.speed = speed;
    }

    public void Move(float deltaTime) {
        position += direction * speed * deltaTime;
    }
}

public class BulletPool {
    private Queue<Bullet> bulletPool = new Queue<Bullet>();

    public Bullet GetBullet(Vector3 position, Vector3 direction, float speed) {
        if (bulletPool.Count > 0) {
            Bullet bullet = bulletPool.Dequeue();
            bullet.MoveTo(position);
            bullet.SetDirection(direction);
            bullet.SetSpeed(speed);
            return bullet;
        } else {
            return new Bullet(position, direction, speed);
        }
    }

    public void RecycleBullet(Bullet bullet) {
        bulletPool.Enqueue(bullet);
    }
}

// 调用代码
BulletPool bulletPool = new BulletPool();
Bullet bullet = bulletPool.GetBullet(new Vector3(0, 0, 0), new Vector3(1, 0, 0), 10f);
bullet.Move(0.1f);
bulletPool.RecycleBullet(bullet);

下面是一些高级用法

本文由作者按照 CC BY 4.0 进行授权