shengjie_yan 9 gadi atpakaļ
vecāks
revīzija
58ee9df14f

+ 6 - 0
DesignPattern.sln

@@ -5,6 +5,8 @@ VisualStudioVersion = 14.0.25420.1
 MinimumVisualStudioVersion = 10.0.40219.1
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FactoryPattern", "FactoryPattern\FactoryPattern.csproj", "{B6F92CD5-5347-4F36-96CB-2ED8B9F66C25}"
 EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SingletonPattern", "SingletonPattern\SingletonPattern.csproj", "{1DC67A01-1D89-4D4B-A7E2-400B191FFB9D}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -15,6 +17,10 @@ Global
 		{B6F92CD5-5347-4F36-96CB-2ED8B9F66C25}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{B6F92CD5-5347-4F36-96CB-2ED8B9F66C25}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{B6F92CD5-5347-4F36-96CB-2ED8B9F66C25}.Release|Any CPU.Build.0 = Release|Any CPU
+		{1DC67A01-1D89-4D4B-A7E2-400B191FFB9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{1DC67A01-1D89-4D4B-A7E2-400B191FFB9D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{1DC67A01-1D89-4D4B-A7E2-400B191FFB9D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{1DC67A01-1D89-4D4B-A7E2-400B191FFB9D}.Release|Any CPU.Build.0 = Release|Any CPU
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

+ 6 - 0
SingletonPattern/App.config

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<configuration>
+    <startup> 
+        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
+    </startup>
+</configuration>

+ 67 - 0
SingletonPattern/Program.cs

@@ -0,0 +1,67 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace SingletonPattern
+{
+    class Program
+    {
+        static void Main(string[] args)
+        {
+            Console.WriteLine("单例模式:");
+            TestStaticSingleton();
+            TestLasyInitialSingleton();
+            TestDoubleLockSingleton();
+        }
+
+        private static void TestStaticSingleton()
+        {
+            Console.WriteLine("静态变量初始化实例");
+
+            Singleton1 singleton1 = Singleton1.Instance();
+            singleton1.GetInfo();
+
+            Console.ReadLine();
+        }
+
+        private static void TestLasyInitialSingleton()
+        {
+            Console.WriteLine("延迟初始化实例");
+
+            Singleton2 singleton2 = Singleton2.Instance();
+            singleton2.GetInfo();
+            singleton2.Reset();
+           
+            Console.ReadLine();
+        }
+
+        private static void TestDoubleLockSingleton()
+        {
+            Console.WriteLine("锁机制确保多线程只产生一个实例");
+
+            for (int i = 0; i < 8; i++)
+            {
+                Thread thread=new Thread(ExecuteInForeground);
+
+                thread.Start();
+            }
+        }
+
+
+        private static void ExecuteInForeground()
+        {
+            Console.WriteLine("Thread {0}: {1}, Priority {2}",
+                              Thread.CurrentThread.ManagedThreadId,
+                              Thread.CurrentThread.ThreadState,
+                              Thread.CurrentThread.Priority);
+
+            Singleton3 singleton3 =Singleton3.Instance();
+            singleton3.GetInfo();
+            Console.WriteLine(singleton3.GetHashCode());
+        }
+    }
+}

+ 36 - 0
SingletonPattern/Properties/AssemblyInfo.cs

@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("SingletonPattern")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("SingletonPattern")]
+[assembly: AssemblyCopyright("Copyright ©  2016")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("1dc67a01-1d89-4d4b-a7e2-400b191ffb9d")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]

+ 35 - 0
SingletonPattern/Singleton1.cs

@@ -0,0 +1,35 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SingletonPattern
+{
+    /// <summary>
+    /// 单例模式实现方式一:
+    /// 静态变量初始化
+    /// </summary>
+    public class Singleton1
+    {
+        /// <summary>
+        /// 定义为static,可以保证变量为线程安全的,即每个线程一个实例
+        /// </summary>
+        private static Singleton1 instance = new Singleton1();
+
+        private Singleton1()
+        {
+            
+        }
+
+        public static Singleton1 Instance()
+        {
+            return instance;
+        }
+
+        public void GetInfo()
+        {
+            Console.WriteLine($"I am {this.GetType().Name}.");
+        }
+    }
+}

+ 43 - 0
SingletonPattern/Singleton2.cs

@@ -0,0 +1,43 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SingletonPattern
+{
+    /// <summary>
+    /// 单例模式实现方式二:
+    /// 延迟初始化
+    /// </summary>
+    public class Singleton2
+    {
+        /// <summary>
+        /// 定义为static,可以保证变量为线程安全的,即每个线程一个实例
+        /// </summary>
+        private static Singleton2 _instance;
+
+        private Singleton2()
+        {
+            
+        }
+
+        public static Singleton2 Instance()
+        {
+            return _instance ?? (_instance = new Singleton2());
+        }
+
+        /// <summary>
+        /// 使用此方法销毁已创建的实例
+        /// </summary>
+        public void Reset()
+        {
+            _instance = null;
+        }
+
+        public void GetInfo()
+        {
+            Console.WriteLine($"I am {this.GetType().Name}.");
+        }
+    }
+}

+ 42 - 0
SingletonPattern/Singleton3.cs

@@ -0,0 +1,42 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SingletonPattern
+{
+    /// <summary>
+    /// 单例模式实现方式三:
+    /// 锁机制,确保多线程只产生一个实例
+    /// </summary>
+    public class Singleton3
+    {
+        private static Singleton3 _instance;
+
+        private static readonly object Locker =new object();
+
+        private Singleton3() { }
+
+        public static Singleton3 Instance()
+        {
+            if (_instance==null)
+            {
+                lock (Locker)
+                {
+                    if (_instance==null)
+                    {
+                        _instance = new Singleton3();
+                    }
+                }
+            }
+
+            return _instance;
+        }
+
+        public void GetInfo()
+        {
+            Console.WriteLine($"I am {this.GetType().Name}.");
+        }
+    }
+}

+ 63 - 0
SingletonPattern/SingletonPattern.csproj

@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{1DC67A01-1D89-4D4B-A7E2-400B191FFB9D}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>SingletonPattern</RootNamespace>
+    <AssemblyName>SingletonPattern</AssemblyName>
+    <TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <PlatformTarget>AnyCPU</PlatformTarget>
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <PlatformTarget>AnyCPU</PlatformTarget>
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Xml.Linq" />
+    <Reference Include="System.Data.DataSetExtensions" />
+    <Reference Include="Microsoft.CSharp" />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Net.Http" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Program.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="Singleton1.cs" />
+    <Compile Include="Singleton2.cs" />
+    <Compile Include="Singleton3.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="App.config" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>