1
0
jeffrey 8 жил өмнө
parent
commit
703c65a6b5

+ 6 - 0
DesignPattern.sln

@@ -29,6 +29,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdapterPattern", "AdapterPa
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompositePattern", "CompositePattern\CompositePattern.csproj", "{EDEE3E18-5C3F-4B91-9EDF-393DC42F5E3F}"
 EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ObserverPattern", "ObserverPattern\ObserverPattern.csproj", "{4C79FD56-5B6A-44A6-A2F1-4F5DBCAEC907}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -87,6 +89,10 @@ Global
 		{EDEE3E18-5C3F-4B91-9EDF-393DC42F5E3F}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{EDEE3E18-5C3F-4B91-9EDF-393DC42F5E3F}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{EDEE3E18-5C3F-4B91-9EDF-393DC42F5E3F}.Release|Any CPU.Build.0 = Release|Any CPU
+		{4C79FD56-5B6A-44A6-A2F1-4F5DBCAEC907}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{4C79FD56-5B6A-44A6-A2F1-4F5DBCAEC907}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{4C79FD56-5B6A-44A6-A2F1-4F5DBCAEC907}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{4C79FD56-5B6A-44A6-A2F1-4F5DBCAEC907}.Release|Any CPU.Build.0 = Release|Any CPU
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

+ 6 - 0
ObserverPattern/App.config

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

+ 46 - 0
ObserverPattern/DelegateImplement/FishingRod.cs

@@ -0,0 +1,46 @@
+using System;
+
+namespace ObserverPattern.DelegateImplement
+{
+    /// <summary>
+    ///     鱼竿
+    /// </summary>
+    public class FishingRod
+    {
+        public delegate void FishingHandler(FishType type); //声明委托
+        public event FishingHandler FishingEvent; //声明事件
+
+        public void Fishing()
+        {
+            Console.WriteLine("开始下钩!");
+
+            //用随机数模拟鱼咬钩,若随机数大于5,通知订阅者
+            var a = new Random(10).Next();
+            var type = (FishType) new Random().Next(0, 5);
+            Console.WriteLine("铃铛:叮叮叮,鱼儿咬钩了");
+            if (FishingEvent != null)
+                FishingEvent(type);
+        }
+    }
+
+
+    /// <summary>
+    ///     垂钓者(观察者)
+    /// </summary>
+    public class FishingMan
+    {
+        public FishingMan(string name)
+        {
+            Name = name;
+        }
+
+        public string Name { get; set; }
+        public int FishCount { get; set; }
+
+        public void Update(FishType type)
+        {
+            FishCount++;
+            Console.WriteLine("{0}:钓到一条[{2}],已经钓到{1}条鱼了!", Name, FishCount, type);
+        }
+    }
+}

+ 12 - 0
ObserverPattern/FishType.cs

@@ -0,0 +1,12 @@
+namespace ObserverPattern
+{
+    public enum FishType
+    {
+        鲫鱼,
+        鲤鱼,
+        黑鱼,
+        青鱼,
+        草鱼,
+        鲈鱼
+    }
+}

+ 64 - 0
ObserverPattern/ObserverPattern.csproj

@@ -0,0 +1,64 @@
+<?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>{4C79FD56-5B6A-44A6-A2F1-4F5DBCAEC907}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>ObserverPattern</RootNamespace>
+    <AssemblyName>ObserverPattern</AssemblyName>
+    <TargetFrameworkVersion>v4.5.2</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="DelegateImplement\FishingRod.cs" />
+    <Compile Include="FishType.cs" />
+    <Compile Include="SimpleImplement\FishingTool.cs" />
+    <Compile Include="Program.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="App.config" />
+  </ItemGroup>
+  <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>

+ 70 - 0
ObserverPattern/Program.cs

@@ -0,0 +1,70 @@
+using System;
+using System.Threading;
+using ObserverPattern.SimpleImplement;
+
+namespace ObserverPattern
+{
+    internal class Program
+    {
+        private static void Main(string[] args)
+        {
+            SimpleObserverTest();
+            Console.ReadLine();
+            Console.WriteLine("=======================");
+            DelegateObserverTest();
+            Console.ReadLine();
+        }
+
+        /// <summary>
+        ///     测试简单实现的观察者模式
+        /// </summary>
+        private static void SimpleObserverTest()
+        {
+            Console.WriteLine("简单实现的观察者模式:");
+            Console.WriteLine("=======================");
+            //1、初始化鱼竿
+            var fishingRod = new FishingRod();
+
+            //2、声明垂钓者
+            var jeff = new FishingMan("圣杰");
+
+            //3、将垂钓者观察鱼竿
+            fishingRod.AddSubscriber(jeff);
+
+            //4、循环钓鱼
+            while (jeff.FishCount < 5)
+            {
+                fishingRod.Fishing();
+                Console.WriteLine("-------------------");
+                //睡眠5s
+                Thread.Sleep(5000);
+            }
+        }
+
+        /// <summary>
+        ///     测试委托实现的观察者模式
+        /// </summary>
+        private static void DelegateObserverTest()
+        {
+            Console.WriteLine("委托实现的观察者模式:");
+            Console.WriteLine("=======================");
+            //1、初始化鱼竿
+            var fishingRod = new DelegateImplement.FishingRod();
+
+            //2、声明垂钓者
+            var jeff = new DelegateImplement.FishingMan("圣杰");
+
+            //3、注册观察者
+            fishingRod.FishingEvent += jeff.Update;
+
+            //4、循环钓鱼
+            while (jeff.FishCount < 5)
+            {
+                fishingRod.Fishing();
+                Console.WriteLine("-------------------");
+                //睡眠5s
+                Thread.Sleep(5000);
+            }
+        }
+    }
+}

+ 36 - 0
ObserverPattern/Properties/AssemblyInfo.cs

@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// 有关程序集的一般信息由以下
+// 控制。更改这些特性值可修改
+// 与程序集关联的信息。
+[assembly: AssemblyTitle("ObserverPattern")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("Microsoft")]
+[assembly: AssemblyProduct("ObserverPattern")]
+[assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+//将 ComVisible 设置为 false 将使此程序集中的类型
+//对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
+//请将此类型的 ComVisible 特性设置为 true。
+[assembly: ComVisible(false)]
+
+// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
+[assembly: Guid("4c79fd56-5b6a-44a6-a2f1-4f5dbcaec907")]
+
+// 程序集的版本信息由下列四个值组成: 
+//
+//      主版本
+//      次版本
+//      生成号
+//      修订号
+//
+//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
+// 方法是按如下所示使用“*”: :
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]

+ 82 - 0
ObserverPattern/SimpleImplement/FishingTool.cs

@@ -0,0 +1,82 @@
+using System;
+using System.Collections.Generic;
+
+namespace ObserverPattern.SimpleImplement
+{
+    /// <summary>
+    ///     钓鱼工具抽象类
+    ///     用来维护订阅者列表,并通知订阅者
+    /// </summary>
+    public abstract class FishingTool
+    {
+        private readonly List<ISubscriber> _subscribers;
+
+        protected FishingTool()
+        {
+            _subscribers = new List<ISubscriber>();
+        }
+
+        public void AddSubscriber(ISubscriber subscriber)
+        {
+            if (!_subscribers.Contains(subscriber))
+                _subscribers.Add(subscriber);
+        }
+
+        public void RemoveSubscriber(ISubscriber subscriber)
+        {
+            if (_subscribers.Contains(subscriber))
+                _subscribers.Remove(subscriber);
+        }
+
+        public void Notify(FishType type)
+        {
+            foreach (var subscriber in _subscribers)
+                subscriber.Update(type);
+        }
+    }
+
+    /// <summary>
+    ///     鱼竿
+    /// </summary>
+    public class FishingRod : FishingTool
+    {
+        public void Fishing()
+        {
+            Console.WriteLine("开始下钩!");
+
+            //用随机数模拟鱼咬钩,若随机数大于5,通知订阅者
+            var type = (FishType) new Random().Next(0, 5);
+            Console.WriteLine("铃铛:叮叮叮,鱼儿咬钩了");
+            Notify(type);
+        }
+    }
+
+    /// <summary>
+    ///     订阅者(观察者)接口
+    ///     由具体的订阅者实现Update()方法
+    /// </summary>
+    public interface ISubscriber
+    {
+        void Update(FishType type);
+    }
+
+    /// <summary>
+    ///     垂钓者实现观察者接口
+    /// </summary>
+    public class FishingMan : ISubscriber
+    {
+        public FishingMan(string name)
+        {
+            Name = name;
+        }
+
+        public string Name { get; set; }
+        public int FishCount { get; set; }
+
+        public void Update(FishType type)
+        {
+            FishCount++;
+            Console.WriteLine("{0}:钓到一条[{2}],已经钓到{1}条鱼了!", Name, FishCount, type);
+        }
+    }
+}