设计模式之单例模式

定义:

某个类只能有一个实例
必须自行创建这个实例
访问方便

三种创建对象的方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //实例化
            Player p = new Player();
            //克隆
            p.Clone();
            //反射
            Activator.CreateInstance<Player>();
        }
    }
    public class Player
    {
        public Player Clone()
        {
           return this.MemberwiseClone() as Player; 
        }
    }
}

实例方法和静态方法的区别

实例方法:实例对象+方法名
静态方法:类名+方法名

构造器(拿到对象的一种手段,初始化对象)



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeTest
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
    public class Player
    {
        private int _hp;
        //无参构造器
        public Player()
        {

        }
        //有参构造器
        public Player(int hp)
        {
            _hp = hp;
        }
       //静态构造器
        static Player()
        {

        }
    }
}

//普通单例模式(1)

using UnityEngine;
using System.Collections;

namespace SingletonPattern  {

    public class Singleton
    {
        //静态变量
        private static Singleton instance;
        //私有构造器
        private Singleton()
        {

        }
        //静态方法
        public static Singleton GetIntance()
        {
            if (instance==null)
            {
                instance=new Singleton()
            }
            return instance;
        }
    }
}

普通单例模式(2)


using UnityEngine;
using System.Collections;

namespace SingletonPattern  {

    public class Singleton
    {
        private static Singleton instance;
        private Singleton()
        {

        }
        //用属性
        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Singleton();
            }
                return instance;
            }
        }
    }
}

属性和方法的关系:属性是一个特殊的方法

泛型单例模式


using UnityEngine;
using System.Collections.Generic;

namespace SingletonPattern  {

    public class Singleton<T> where T:class,new()
    {
        private static T instance;
        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new T();
            }
                return instance;
            }
        }
    }
}

“`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值