zoukankan      html  css  js  c++  java
  • Unity创建实例:普通实例,单例,线程单例

    //Unity容器,默认情况下生成普通对象
    //在注册时传入参数new ContainerControlledLifetimeManager(),可以创建单例对象
    //在注册的时候传入参数new PerThreadLifetimeManager(),可以创建线程单例对象
    //容器不知可以生成对象,还可以管理对象的生命周期
    IUnityContainer ucontainer = new UnityContainer();//ContainerControlledLifetimeManager
    ucontainer.RegisterType<IPhone, ApplePhone>(new ContainerControlledLifetimeManager());
    //单例是只要通过容器生成的对象都是同一个实例,在系统中不同地方获取的单利都是同一个实例
    IPhone phone1 = ucontainer.Resolve<IPhone>();
    IPhone phone2 = ucontainer.Resolve<IPhone>();
    Console.WriteLine($"{object.ReferenceEquals(phone1, phone2)}");

    //线程单例:同一个线程就是同一个实例,不同线程就是不同的实例
    IPhone phone1 = null;
    IPhone phone2 = null;
    IPhone phone3 = null;
    IPhone phone4 = null;
    IPhone phone5 = null;
    IUnityContainer ucontainer = new UnityContainer();
    ucontainer.RegisterType<IPhone, AndroidPhone>(new PerThreadLifetimeManager());
    phone1 = ucontainer.Resolve<IPhone>();
    phone2 = ucontainer.Resolve<IPhone>();
    Console.WriteLine($"12的当前线程ID:{Thread.CurrentThread.ManagedThreadId}");

    new Action(() =>
    {
    phone3 = ucontainer.Resolve<IPhone>();
    Console.WriteLine($"3的当前线程ID:{Thread.CurrentThread.ManagedThreadId}");
    }).BeginInvoke(null, null);

    new Action(() =>
    {
    phone4 = ucontainer.Resolve<IPhone>();
    Console.WriteLine($"4的当前线程ID:{Thread.CurrentThread.ManagedThreadId}");
    }).BeginInvoke(arg =>
    {
    phone5 = ucontainer.Resolve<IPhone>();
    Console.WriteLine($"5的当前线程ID:{Thread.CurrentThread.ManagedThreadId}");
    }, null);
    Thread.Sleep(5000);
    Console.WriteLine($"12:{object.ReferenceEquals(phone1, phone2)}");
    Console.WriteLine($"13:{object.ReferenceEquals(phone1, phone3)}");
    Console.WriteLine($"14:{object.ReferenceEquals(phone1, phone4)}");
    Console.WriteLine($"34:{object.ReferenceEquals(phone3, phone4)}");
    Console.WriteLine($"45:{object.ReferenceEquals(phone4, phone5)}");

  • 相关阅读:
    关于2019-nCoV事件中新媒体的作用
    评估移民宇宙计划
    关于2019-nCoV事件,分析自己的焦虑心理
    肺炎阴云仍未散去,今天捡到一个贝壳
    关于新型肺炎,重点是毒性
    提高效率的方法
    《白说》读书笔记
    MIPS下载运行busybox
    camera模组笔记
    求知领域
  • 原文地址:https://www.cnblogs.com/fblogs/p/12263436.html
Copyright © 2011-2022 走看看