{C#}设计模式辨析.享元
2021-08-08 本文已影响0人
码农猫爸
背景
- 共享重复对象,大量重复时可显著节约内存并提升速度
- 享元:共享元数据
- flyweight:苍蝇般轻量级
示例
using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;
namespace DesignPattern_Flyweight
{
// 子弹类,可重用
public class Bullet
{
public string Name;
public int Size;
public Bullet(string name, int size)
{
Name = name;
Size = size;
}
public override string ToString()
=> $"name={Name}";
}
// 子弹工厂,拥有子弹集合及其操作
public class BulletFactory
{
private List<Bullet> bullets = new List<Bullet>();
public void Add(Bullet bullet)
{
if (bullets.Any(x => x.Name == bullet.Name)) return;
bullets.Add(bullet);
}
public int Count => bullets.Count;
public Bullet this[int index] => bullets[index];
}
class Program
{
static void Main(string[] args)
{
var bullets = new BulletFactory();
bullets.Add(new Bullet("small", 10));
bullets.Add(new Bullet("middle", 20));
bullets.Add(new Bullet("big", 30));
_DrawRainOfBullet();
void _DrawRainOfBullet()
{
var rand = new Random();
for (int i = 0; i < 10; i++)
{
int x = rand.Next(100);
int y = rand.Next(100);
int at = rand.Next(bullets.Count);
WriteLine($"x={x}, y={y}, {bullets[at]}");
}
ReadKey();
}
}
}
}