常规单例模式-简单的
using System;
using System. Collections. Generic;
using System. Linq;
using System. Text;
using System. Threading. Tasks;
namespace Clone
{
class Program
{
abstract class property
{
public abstract property Clone ( ) ;
}
class ConcreatProperty
{
public static ConcreatProperty OnlyObj = null ;
private string str;
public string Str
{
get
{
return str;
}
set
{
str = value ;
}
}
public static ConcreatProperty Clone ( )
{
if ( OnlyObj == null )
{
OnlyObj = new ConcreatProperty ( ) ;
OnlyObj. Str = "我是克隆" ;
}
return OnlyObj;
}
}
static void Main ( string [ ] args)
{
ConcreatProperty t1, t2, t3;
t1 = ConcreatProperty. Clone ( ) ;
t2 = ConcreatProperty. Clone ( ) ;
t3 = ConcreatProperty. Clone ( ) ;
Console. WriteLine ( t2 == t1&& t1== t3) ;
Console. ReadKey ( ) ;
}
}
}
安全单例模式
using System;
using System. Collections. Generic;
using System. Linq;
using System. Text;
using System. Threading. Tasks;
namespace Clone
{
class Program
{
abstract class property
{
public abstract property Clone ( ) ;
}
class ConcreatProperty
{
public static ConcreatProperty OnlyObj = null ;
private static readonly object lockObj = new object ( ) ;
private string str;
public string Str
{
get
{
return str;
}
set
{
str = value ;
}
}
public static ConcreatProperty Clone ( )
{
if ( OnlyObj == null )
{
lock ( lockObj)
{
if ( OnlyObj == null )
{
OnlyObj = new ConcreatProperty ( ) ;
OnlyObj. Str = "我是克隆" ;
}
}
}
return OnlyObj;
}
}
static void Main ( string [ ] args)
{
ConcreatProperty t1, t2, t3;
t1 = ConcreatProperty. Clone ( ) ;
t2 = ConcreatProperty. Clone ( ) ;
t3 = ConcreatProperty. Clone ( ) ;
Console. WriteLine ( t2 == t1&& t1== t3) ;
Console. WriteLine ( t1. Str) ;
Console. ReadKey ( ) ;
}
}
}