Singleton (单件模式)

本文介绍单例模式的设计理念,确保类只有一个实例并提供全局访问点。通过C#代码实现单例模式,展示如何创建唯一实例并通过子类化进行扩展。

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

意图: 保证一个类仅有一个实例,并提供一个访问它的全局访问点。

使用性:

当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时。 当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。

代码:

namespace Singleton_DesignPattern
{
using System;

class Singleton
{
private static Singleton _instance;

public static Singleton Instance()
{
if (_instance == null)
_instance = new Singleton();
return _instance;
}
protected Singleton(){}

// Just to prove only a single instance exists
private int x = 0;
public void SetX(int newVal) {x = newVal;}
public int GetX(){return x;}
}

public class Client
{
public static int Main(string[] args)
{
int val;
// can't call new, because constructor is protected
Singleton FirstSingleton = Singleton.Instance();
Singleton SecondSingleton = Singleton.Instance();

// Now we have two variables, but both should refer to the same object
// Let's prove this, by setting a value using one variable, and
// (hopefully!) retrieving the same value using the second variable
FirstSingleton.SetX(4);
Console.WriteLine("Using first variable for singleton, set x to 4");

val = SecondSingleton.GetX();
Console.WriteLine("Using second variable for singleton, value retrieved = {0}", val);
return 0;
}
}
}

<!-- Message body ''"" -->
<script type="text/javascript"> //<![CDATA[ Sys.WebForms.PageRequestManager._initialize('AjaxHolder$scriptmanager1', document.getElementById('Form1')); Sys.WebForms.PageRequestManager.getInstance()._updateControls(['tAjaxHolder$UpdatePanel1'], [], [], 90); //]]> </script>
<style type="text/css"> td { font-size: 12px } .commentTextBox { font-family : Verdana; font-size: 13px; }</style> <!--Beging Temp Save--><style type="text/css"> .userData { BEHAVIOR: url(#default#userdata) } </style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值