Browse Source

命令模式

jeffrey 9 years ago
parent
commit
e129b99866

+ 6 - 0
CommandPattern/App.config

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

+ 59 - 0
CommandPattern/CommandPattern.csproj

@@ -0,0 +1,59 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.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>{D49AD28A-0DF4-4D25-8CB7-4F72371E311F}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>CommandPattern</RootNamespace>
+    <AssemblyName>CommandPattern</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+  </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.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Invoker.cs" />
+    <Compile Include="Program.cs" />
+    <Compile Include="Properties\AssemblyInfo.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>

+ 178 - 0
CommandPattern/Invoker.cs

@@ -0,0 +1,178 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace CommandPattern
+{
+    /// <summary>
+    /// 调用者角色
+    /// </summary>
+    public class Invoker
+    {
+        /// <summary>
+        /// 申明调用的命令,并用构造函数注入
+        /// </summary>
+        private readonly Command command;
+
+        public string InovkerName { get; set; }
+
+        public Invoker(Command command)
+        {
+            this.command = command;
+        }
+
+        /// <summary>
+        /// 调用以执行具体命令
+        /// </summary>
+        public void Invoke()
+        {
+            Console.WriteLine(string.Format("『{0}』下达命令:{1}", this.InovkerName, this.command.CommandName));
+            this.command.Execute();
+        }
+    }
+
+    /// <summary>
+    /// 命令者角色
+    /// </summary>
+    public abstract class Command
+    {
+        protected readonly Receiver receiver;
+
+        public string CommandName { get; set; }
+
+        public Command(Receiver receiver)
+        {
+            this.receiver = receiver;
+        }
+
+        /// <summary>
+        /// 抽象执行具体命令方法
+        /// 由之类实现
+        /// </summary>
+        public abstract void Execute();
+    }
+
+    /// <summary>
+    /// 武力收复台湾命令
+    /// </summary>
+    public class RecaptureTaiwanByFocusCommand : Command
+    {
+        string commandName = "武力收复台湾!";
+
+        /// <summary>
+        /// 重写默认构造函数,指定默认接收者
+        /// 以降低高层模块对底层模块的依赖
+        /// </summary>
+        public RecaptureTaiwanByFocusCommand() :
+            base(new OperationCenter())
+        {
+            base.CommandName = commandName;
+        }
+
+        /// <summary>
+        /// 也可通过构造函数重新指定接收者
+        /// </summary>
+        /// <param name="receiver"></param>
+        public RecaptureTaiwanByFocusCommand(Receiver receiver)
+            : base(receiver)
+        {
+            base.CommandName = commandName;
+        }
+
+        public override void Execute()
+        {
+            this.receiver.Plan();
+            this.receiver.Action();
+        }
+    }
+
+    /// <summary>
+    /// 和平方式收复台湾命令
+    /// </summary>
+    public class RecaptureTaiwanByPeaceCommand : Command
+    {
+        string commandName = "和平收复台湾!";
+        /// <summary>
+        /// 重写默认构造函数,指定默认接收者
+        /// 以降低高层模块对底层模块的依赖
+        /// </summary>
+        public RecaptureTaiwanByPeaceCommand() :
+            base(new NegotiationCenter())
+        {
+            base.CommandName = commandName;
+        }
+
+        /// <summary>
+        /// 也可通过构造函数重新指定接收者
+        /// </summary>
+        /// <param name="receiver"></param>
+        public RecaptureTaiwanByPeaceCommand(Receiver receiver)
+            : base(receiver)
+        {
+            base.CommandName = commandName;
+        }
+
+        public override void Execute()
+        {
+            this.receiver.Plan();
+            this.receiver.Action();
+        }
+    }
+
+
+    /// <summary>
+    /// 接收者角色
+    /// </summary>
+    public abstract class Receiver
+    {
+        protected string ReceiverName { get; set; }
+
+        //定义每个执行者都必须处理的业务逻辑
+        public abstract void Plan();
+        public abstract void Action();
+    }
+
+
+    /// <summary>
+    /// 作战中心
+    /// </summary>
+    public class OperationCenter : Receiver
+    {
+        public OperationCenter()
+        {
+            this.ReceiverName = "作战中心";
+        }
+        public override void Plan()
+        {
+            Console.WriteLine(string.Format("{0}:制定作战计划。", this.ReceiverName));
+        }
+
+        public override void Action()
+        {
+            Console.WriteLine(string.Format("{0}:海陆空按照即定作战计划作战,收复台湾!", this.ReceiverName));
+        }
+    }
+
+    /// <summary>
+    /// 谈判中心
+    /// </summary>
+    public class NegotiationCenter : Receiver
+    {
+        public NegotiationCenter()
+        {
+            this.ReceiverName = "谈判中心";
+        }
+        public override void Plan()
+        {
+            Console.WriteLine(string.Format("{0}:制定谈判计划。", this.ReceiverName));
+        }
+
+        public override void Action()
+        {
+            Console.WriteLine(string.Format("{0}:落实谈判结果,收复台湾!", this.ReceiverName));
+        }
+    }
+
+}

+ 36 - 0
CommandPattern/Program.cs

@@ -0,0 +1,36 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace CommandPattern
+{
+    class Program
+    {
+        static void Main(string[] args)
+        {
+            //申明和平收复台湾命令
+            Command focusCommand = new RecaptureTaiwanByPeaceCommand();
+
+            //申明调用者
+            Invoker invoker = new Invoker(focusCommand);
+            invoker.InovkerName = "习大大";
+
+            //下达命令
+            invoker.Invoke();
+
+            Console.WriteLine("-------------------------------");
+
+            //申明武力收复台湾命令
+            Command peaceCommand = new RecaptureTaiwanByFocusCommand();
+
+            invoker = new Invoker(peaceCommand);
+            invoker.InovkerName = "习大大";
+
+            invoker.Invoke();
+
+            Console.ReadLine();
+        }
+    }
+}

+ 36 - 0
CommandPattern/Properties/AssemblyInfo.cs

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

+ 7 - 3
DesignPattern.sln

@@ -1,8 +1,6 @@
 
 Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 14
-VisualStudioVersion = 14.0.25420.1
-MinimumVisualStudioVersion = 10.0.40219.1
+# Visual Studio 2012
 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}"
@@ -17,6 +15,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProxyPattern", "ProxyPatter
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MediatorPattern", "MediatorPattern\MediatorPattern.csproj", "{EA608B4B-5203-42F6-891D-59BEB23F3B38}"
 EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CommandPattern", "CommandPattern\CommandPattern.csproj", "{D49AD28A-0DF4-4D25-8CB7-4F72371E311F}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -51,6 +51,10 @@ Global
 		{EA608B4B-5203-42F6-891D-59BEB23F3B38}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{EA608B4B-5203-42F6-891D-59BEB23F3B38}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{EA608B4B-5203-42F6-891D-59BEB23F3B38}.Release|Any CPU.Build.0 = Release|Any CPU
+		{D49AD28A-0DF4-4D25-8CB7-4F72371E311F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{D49AD28A-0DF4-4D25-8CB7-4F72371E311F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{D49AD28A-0DF4-4D25-8CB7-4F72371E311F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{D49AD28A-0DF4-4D25-8CB7-4F72371E311F}.Release|Any CPU.Build.0 = Release|Any CPU
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE