How to delay static initialization within a property

前端 未结 2 641
一生所求
一生所求 2020-12-12 07:37

I\'ve made a class that is a cross between a singleton (fifth version) and a (dependency injectable) factory. Call this a \"Mono-Factory?\" It works, and looks like this:<

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 07:53

    A few hints:

    Check out Generics

    I avoid initialization using a static. This can cause odd problems in practice. For example if what you're constructing throws an error then the windows loader will tell you there's a problem but won't tell you what. Your code is never actually invoked so you don't have a chance for an exception to handle the problem. I construct the first instance when it's used the first time. Here's an example:

        private static OrderCompletion instance;
    
        /// 
        /// Get the single instance of the object
        /// 
        public static OrderCompletion Instance
        {
            get
            {
                lock (typeof(OrderCompletion))
                {
                    if (instance == null)
                        instance = new OrderCompletion();
                }
                return instance;
            }
        }
    

提交回复
热议问题