{C#}设计模式辨析.享元

2021-08-08  本文已影响0人  码农猫爸

背景

示例

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();
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读