zoukankan      html  css  js  c++  java
  • 单件模式 Singleton

    故事:

      每个公司/工厂通常只有一个前台(有的没有),有或者没有这是一个问题。

    建模:

      前台:能够提供各种服务的前台。

    类图:

    实现:

    FrontDesk

    namespace Singleton
    {
        public class FrontDesk
        {
            static FrontDesk current;
            private FrontDesk()
            {
                Console.WriteLine("新建前台成功");
            }
            public static FrontDesk Instance()
            {
                if (current == null)
                {
                    current = new FrontDesk();
                    return current;
                }
                return current;
            }
    
            public static bool Exist()
            {
                if (current == null)
                    return false;
                else
                    return true;
            }
        }
    }

    Program

    namespace Singleton
    {
        class Program
        {
            static void Main(string[] args)
            {
                if (FrontDesk.Exist())
                {
                    Console.WriteLine("\n已存在一个前台!\n");
                }
                else
                {
                    Console.WriteLine("\n当前不存在前台!\n");
                    FrontDesk frontDesk = FrontDesk.Instance();
                    if (FrontDesk.Exist())
                    {
                        Console.WriteLine("前台有人值班,可提供服务");
                    }
                }
            }
        }
    }

    效果:

  • 相关阅读:
    [PA2014]Muzeum
    [AMPPZ2014]Jaskinia
    [PA2015]Rozstaw szyn
    LOJ 6713 「EC Final 2019」狄利克雷 k 次根 加强版
    Problem. R
    51nod 2583 数论只会Gcd
    51nod 1847 奇怪的数学题
    51nod 1575 Gcd and Lcm
    Problem. Q
    CF868G El Toll Caves
  • 原文地址:https://www.cnblogs.com/jiejue/p/2712319.html
Copyright © 2011-2022 走看看