定义:
某个类只能有一个实例
必须自行创建这个实例
访问方便
三种创建对象的方法
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;
}
}
}
}
“`