zoukankan      html  css  js  c++  java
  • 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 ();

    }
    }
    }

  • 相关阅读:
    移动端调试解决方案-转载
    移动端调试工具-Weinre
    css颜色大全-转载
    目录
    多版本python import 问题解决方案
    annoy安装
    word2vec
    GBDT
    Adaptive Boosting
    融合模型Aggregation
  • 原文地址:https://www.cnblogs.com/ouyangJJ/p/5828100.html
Copyright © 2011-2022 走看看