单例模式(Singleton Pattern)属于创建型模式,单例类只能有一个实例,并且由它自己创建。
比如游戏中的一个协议控制器,有且只有一个实例。
C#代码:
using System;
namespace ConsoleApp
{
public class ProtocolController
{
private static ProtocolController _instance;
public static ProtocolController getInstance()
{
if (_instance == null)
_instance = new ProtocolController();
return _instance;
}
public void SendProtocol(string protocolContent)
{
Console.WriteLine("send protocol to gameserver :" + protocolContent);
}
public void ConnectServer(string host, int port)
{
Console.WriteLine(string.Format("connect server success: host={0}, port={1}:", host, port));
}
}
public class Program
{
static void Main(string[] args)
{
ProtocolController.getInstance().ConnectServer("www.baaoo.com", 22);
ProtocolController.getInstance().SendProtocol("Login Protocol");
Console.Read();
}
}
}