• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
高明无思ThoughtInWork
博客园    首页    新随笔    联系   管理    订阅  订阅

简单点的,如何创建使用类,单例还是多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();
        }
    }

posted @ 2013-01-10 22:34  高明无思  阅读(1580)  评论(7)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3