首页 > 代码库 > C# 单例模式
C# 单例模式
理解:1.确保只有一个实例 2.提供一个全局访问点,大白话就是:不能在其他类new 出来;
代码:
using System;
namespace SingletonDemo
{
//角色类,单例模式
class Player{
//字段
public string name;
public int hp;
public int Mhp;
public int level;
//共有属性
//共有方法
public void BeAttack(){
hp -= 10;
if(hp<=0){
Console.WriteLine ("die");
}
}
public void GetExp(){
level++;
if (level >= 2) {
hp++;
Console.WriteLine ("life add one");
}
}
//3.提供实例的接口(可以是属性,或方法)
public static Player GetInstance(){
if(null==_instance){
_instance = new Player ();
}
return _instance;
}
//1.私有化构造方法
private Player(){
}
//2.类的内部提供一个静态实例
private static Player _instance;
}
//背包类
class Bag{
public void GetLife(){
Player p = Player.GetInstance ();
p.hp += 10;
p.hp = p.hp > p.Mhp ? p.Mhp : p.hp;
}
}
class MainClass
{
public static void Main (string[] args)
{
Player p = Player.GetInstance ();
p.name="jack";
p.hp = 50;
p.Mhp = 100;
p.level = 1;
Bag bag = new Bag ();
bag.GetLife ();
Console.WriteLine ("Player Name:"+p.name+" Player HP:"+p.hp+" Level:"+p.level);
p.BeAttack ();
p.GetExp ();
Console.WriteLine ("Player Name:"+p.name+" Player HP:"+p.hp+" Level:"+p.level);
Console.ReadKey ();
}
}
}
C# 单例模式