My Singleton in C#

博客展示了一段C#代码,实现了单例模式。定义了SingletonPage类,通过保护构造函数确保单例,提供NewCheckOutPage方法创建实例。还包含TestApp类进行测试,多次调用创建实例方法,验证单例模式的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//MySingleton
using System;
//SingletonPage Class
class SingletonPage
{
 //Fields
 protected static SingletonPage checkoutpage;
 

 //Constructor is protected to ensure Singleton
 protected SingletonPage()
 {
  Console.WriteLine("if you see this line,then the only one instence is created!");
 }

 //Use this to Create SingletonPage instance
 public static SingletonPage NewCheckOutPage()
 {
  if (checkoutpage==null)
     checkoutpage= new SingletonPage();
  return checkoutpage;
 }

};
//-------------------------------------End of SingletonPage Class


//TestApp
class TestApp
{
 public static void Main(string[] args)
 {
  Console.WriteLine("'create' pagea:");
  SingletonPage pagea=SingletonPage.NewCheckOutPage();

        Console.WriteLine("'create' pageb:");
  SingletonPage pageb=SingletonPage.NewCheckOutPage();
  
  Console.WriteLine("'create' pagec:");
  SingletonPage pagec=SingletonPage.NewCheckOutPage();
  
  Console.WriteLine("'create' paged:");
  SingletonPage paged=SingletonPage.NewCheckOutPage();

  while(true){}
 }
};

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值