简单点的,如何创建使用类,单例还是多New几个,区别在哪儿,性能还是需求


使用和创建一只Dog,我经常这样使用,或者组合其中的几个,当然其中有单例模式,也不知道别人一般怎样创建。

单例模式一般用于像数据库访问类这样的东西,因为多也没用,只是不知道只有一个够不够用,哈哈,这问题,就是什么时候用单例,什么时候需要多New几个,取决于性能还是需求呢?倒想请大牛指点指点

public class Dog
    {
        private static Dog _instance = null;
        public static Dog Instance
        {
            get {
                if (_instance == null)
                    _instance = new Dog();
                return _instance;
            }
        }

        public static Dog CreateOne()
        {
            return new Dog();
        }

        public static Dog CreateTwo()
        {
            return Dog.Instance;
        }

        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class Execute
    {
        //创建Dog方式一
        Dog dog = Dog.Instance;

        //创建Dog方式二
        Dog dog2 = new Dog();

        //创建Dog方式三,四
        Dog dog3 = Dog.CreateOne();
        Dog dog4 = Dog.CreateTwo();

        //创建方式五
        public Dog GetADog()
        {
            return this.CreateDog();
        }
        public Dog CreateDog()
        {
            return new Dog();
        }
    }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM