zoukankan      html  css  js  c++  java
  • 设计模式-单例模式

    简介

       通过单例模式保证系统当中一个类只能拥有一个实例

     实现方式

      构造方法私有化,创建一个private类型的对象,调用的时候不能通过new关键字实例化该对象,提供静态方法创建一个唯一对象供其他类使用。

    单线程情况下单例模式

     public class UserSingleton
        {
    
           private static UserSingleton userSingleton =null;
            private UserSingleton()
            {
                Console.WriteLine($"我的线程号:{Thread.GetCurrentProcessorId()};id:{Thread.CurrentThread.ManagedThreadId}");
    
            }
            public static UserSingleton GetInstance()
            {
                if (userSingleton == null)
                {
                       userSingleton = new UserSingleton();
                }
                return userSingleton;
            }
            public void getUserList()
            {
                Console.WriteLine("我是影魔");
            
            }
        }

    多线程

     多线程并发同时去创建对象的时候可能会多次new对象

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace singleton
    {
        public class UserStaticSingleton
        {
    
            private static UserStaticSingleton userSingleton = null;
            static UserStaticSingleton()
            {
           //在静态构造方法当中去new userSingleton 保证多线程情况下,也只new一次对象 userSingleton
    = new UserStaticSingleton(); } public static UserStaticSingleton GetInstance() { return userSingleton; } public void getUserList() { Console.WriteLine("我是影魔"); } } }
  • 相关阅读:
    编程习俗和设计模式
    Design Patterns Quick Memo
    Monty Hall Problem
    RPG game: the lost Roman Army
    A Geeky Game Idea
    App自动化测试:等待webview页面数据加载完成
    Android自动化测试元素定位
    IOS苹果开发者免费证书申请&使用Xcode打包
    pytest测试夹具(fixture)简介
    Unittest与Pytest参数化区别
  • 原文地址:https://www.cnblogs.com/zhengyazhao/p/10761945.html
Copyright © 2011-2022 走看看