使用篇八,对象池

在开头

相信看到对象池,大家是很熟悉了
就算你不熟悉,如果你在**** 搜索的话,我相信可以搜索到 一堆开手枪的 unity版本对象池
那么IF的有什么区别?IF主要提供了三种对象池
1、自动实例化的对象池
2、自己个性化管理生命周期的对象池
3、基类对象池,这是啥?简单讲解:声明一个动物的对象池,你可以取出猫,同时也可以取出狗

上马,上马

    public class PoolTest : Test
    {
        public interface IObject { }
        public class Obj_A : IObject { }
        public class Obj_B : IObject { }

        private void FastExample()
        {
            Log.L("Create a auto create  pool");
            ActivatorCreatePool<Obj_A> pool = new ActivatorCreatePool<Obj_A>();
            Log.L("Get an instance from  pool");
            var _obj = pool.Get();
            Log.L($"the type of instance is {_obj.GetType()}");
            Log.L("Let's put the instance to pool");
            pool.Set(_obj);
        }
        private class MyPool : ObjectPool<Obj_A>
        {
            protected override Obj_A CreatNew(IEventArgs arg)
            {
                return new Obj_A();
            }
        }
        private void NormalTest()
        {
            Log.L("Create a auto create  pool");
            MyPool pool = new MyPool();
            Log.L("Get an instance from  pool");
            var _obj = pool.Get();
            Log.L($"the type of instance is {_obj.GetType()}");
            Log.L("Let's put the instance to pool");
            pool.Set(_obj);
        }

        private class MutiPool : BaseTypePool<IObject> { }

        private void MutiTest()
        {
            Log.L("Create a auto create  pool");
            MutiPool pool = new MutiPool();
            Log.L("Get an instance  A   from  pool");

            IObject _obj = pool.Get<Obj_A>();
            Log.L($"the type of instance is {_obj.GetType()}");
            Log.L("Let's put the instance to pool");
            pool.Set(_obj);

            Log.L("Get an instance  B from  pool");

             _obj = pool.Get<Obj_B>();
            Log.L($"the type of instance is {_obj.GetType()}");
            Log.L("Let's put the instance to pool");
            pool.Set(_obj);


        }
        protected override void Start()
        {
            Log.L("--------------------------");
            FastExample();
            Log.L("--------------------------");
            NormalTest();
            Log.L("--------------------------");
            MutiTest();
        }

        protected override void Stop()
        {
        }

        protected override void Update()
        {
        }
    }


让我们来看看结果,用起来很简单吧

使用篇八,对象池

上一篇:Java多线程 - 线程池的七大参数?手写一个线程池?


下一篇:Python多线程并发时通过线程池限流