使用篇八,对象池

2021/7/15 6:08:07

本文主要是介绍使用篇八,对象池,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

在开头

相信看到对象池,大家是很熟悉了
就算你不熟悉,如果你在CSDN 搜索的话,我相信可以搜索到 一堆开手枪的 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()
        {
        }
    }


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

在这里插入图片描述



这篇关于使用篇八,对象池的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程