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)}");

  • 相关阅读:
    LightOj 1027 A Dangerous Maze
    hdu 4738 Caocao's Bridges(割边)
    数论模板
    Codeforces Round #316 (Div. 2) D. Tree Requests(dsu)
    Educational Codeforces Round 2 E. Lomsat gelral(dsu)
    qa问答机器人pysparnn问题的召回
    pysparnn 模块使用,相似句子召回
    pytorch seq2seq闲聊机器人beam search返回结果
    pytorch seq2seq闲聊机器人加入attention机制
    python 中自带的堆模块heapq
  • 原文地址:https://www.cnblogs.com/fblogs/p/12263436.html
Copyright © 2011-2022 走看看