设计模式之单例模式
来源:互联网 发布:百川考试软件怎么样 编辑:程序博客网 时间:2024/06/10 02:48
定义:
某个类只能有一个实例
必须自行创建这个实例
访问方便
三种创建对象的方法
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
- 设计模式之 单例设计模式
- 设计模式之 单例设计模式
- 设计模式之单例设计模式
- 设计模式之-----------单例设计模式
- 设计模式之:单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之-单例设计模式
- 设计模式之单例设计模式 标签: 设计模式
- 设计模式之单例
- 设计模式之单例
- 设计模式之 单例
- Using table loop for filter
- Unity-ScrollRect-循环播放图片(确实没有转载是真的)
- C3P0工具类
- 设计模式之工厂模式
- Hexo 阅读量 api.leancloud.cn 解析失败
- 设计模式之单例模式
- Linux基础——linux和gcc的介绍
- 为什么要进行日志测试和如何进行日志测试?
- 【深度学习】Attention Model详解
- 静态链表 C++
- ST7735学习
- LightOj-1029-Civil and Evil Engineer
- 软件之母—格蕾丝·霍波
- 干货!三步走带你搞定秋招面试!