瀏覽代碼

中介者模式

shengjie_yan 9 年之前
父節點
當前提交
374fad8b8e

+ 6 - 0
DesignPattern.sln

@@ -15,6 +15,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TemplateMethodPattern", "Te
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProxyPattern", "ProxyPattern\ProxyPattern.csproj", "{DA636B4D-244C-40A4-9B34-63CB9DC45C2F}"
 EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MediatorPattern", "MediatorPattern\MediatorPattern.csproj", "{EA608B4B-5203-42F6-891D-59BEB23F3B38}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -45,6 +47,10 @@ Global
 		{DA636B4D-244C-40A4-9B34-63CB9DC45C2F}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{DA636B4D-244C-40A4-9B34-63CB9DC45C2F}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{DA636B4D-244C-40A4-9B34-63CB9DC45C2F}.Release|Any CPU.Build.0 = Release|Any CPU
+		{EA608B4B-5203-42F6-891D-59BEB23F3B38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{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
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

+ 6 - 0
MediatorPattern/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>

+ 217 - 0
MediatorPattern/Mediator.cs

@@ -0,0 +1,217 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace MediatorPattern
+{
+    /// <summary>
+    /// 抽象角色(模块)
+    /// 主要实现中介的依赖注入
+    /// </summary>
+    public abstract class Role
+    {
+        protected AbstractMediator mediator;
+
+        public Role(AbstractMediator mediator)
+        {
+            this.mediator = mediator;
+        }
+    }
+
+    /// <summary>
+    /// 购房(者)市场
+    /// </summary>
+    public class HomeBuyer : Role
+    {
+        private readonly string name = "购房市场:";
+        public HomeBuyer(AbstractMediator mediator)
+            : base(mediator)
+        {
+
+        }
+        private static int requirement = 800;//购房需求
+
+        public void BuyHouse(int num)
+        {
+            string rule = mediator.GetRule();
+
+            Console.WriteLine(name + "需要买房:" + num + "套");
+
+            if (rule != "LimitBuy")
+            {
+                requirement += num;
+            }
+            else
+            {
+                Console.WriteLine(name + "国家实例了限购政策,不允许购买");
+            }
+        }
+
+        /// <summary>
+        /// 签订购房合同
+        /// </summary>
+        /// <param name="num"></param>
+        public void SignAgreement(int num)
+        {
+            requirement -= num;
+            Console.WriteLine(string.Format("{0}成功购房{1}套", name, num));
+        }
+
+        public int GetRequirement()
+        {
+            return requirement;
+        }
+    }
+
+    /// <summary>
+    /// 房地产商
+    /// </summary>
+    public class Builder : Role
+    {
+        private readonly string name = "房地产商:";
+        public Builder(AbstractMediator mediator)
+            : base(mediator)
+        {
+
+        }
+
+        private static int houseNum = 1000;
+
+        public void BuildHouse()
+        {
+            int requirement = mediator.GetBuyRequirement();
+            if (houseNum < requirement)
+            {
+                //房源不够,立马新建
+                int needBuild = requirement - houseNum + 100;
+                Console.WriteLine(name + "建房:" + needBuild + "套");
+                houseNum += needBuild;
+            }
+        }
+
+        public void SaleHouse(int num)
+        {
+            if (houseNum < num)
+            {
+                string rule = mediator.GetRule();
+
+                if (rule != "LimitBuild")
+                {
+                    Console.WriteLine(name + "房源不够,正在建设中");
+                    this.BuildHouse();
+                }
+            }
+            else
+            {
+                houseNum -= num;
+                Console.WriteLine(name + "卖房:" + num + "套");
+                //告诉购房者签订合同
+                mediator.HomeBuyer.SignAgreement(num);
+            }
+        }
+
+        public int ShowHouseNum()
+        {
+            return houseNum;
+        }
+    }
+
+    /// <summary>
+    /// 住建局
+    /// </summary>
+    public class ControlCenter : Role
+    {
+        public ControlCenter(AbstractMediator mediator)
+            : base(mediator)
+        {
+
+        }
+        private readonly string name = "住建局:";
+        private static string rule;
+
+        /// <summary>
+        /// 当需大于供,限购
+        /// 当供大于需,限建
+        /// </summary>
+        public void Limit()
+        {
+            int requirement = mediator.GetBuyRequirement();
+            int buildingNum = mediator.GetCurrentHouseNumber();
+
+            string strs = string.Format("{0}目前购房需求为:{1}套;现有房源:{2}套。", name,requirement, buildingNum);
+
+            if (requirement > buildingNum)
+            {
+                Console.WriteLine(strs + "供小于需,开始实施限购政策");
+                rule = "LimitBuy";
+            }
+            else
+            {
+                Console.WriteLine(strs + "供大于需,开始实施限建政策");
+                rule = "LimitBuild";
+            }
+        }
+
+        public string ShowRule()
+        {
+            return rule;
+        }
+
+    }
+
+    /// <summary>
+    /// 抽象中介,定义各模块依赖的功能
+    /// </summary>
+    public abstract class AbstractMediator
+    {
+        /// <summary>
+        /// 使用属性注入
+        /// 因为中介可能只需要和部分角色(模块)交互
+        /// </summary>
+        public HomeBuyer HomeBuyer { get; set; }
+        public Builder HouseBuilder { get; set; }
+        public ControlCenter ControlCenter { get; set; }
+
+        /// <summary>
+        /// 获取购房需求
+        /// </summary>
+        /// <returns></returns>
+        public abstract int GetBuyRequirement();
+
+        /// <summary>
+        /// 获取房源数目
+        /// </summary>
+        /// <returns></returns>
+        public abstract int GetCurrentHouseNumber();
+
+        /// <summary>
+        /// 获取楼市政策
+        /// </summary>
+        /// <returns></returns>
+        public abstract string GetRule();
+
+    }
+
+    /// <summary>
+    /// 具体中介,实现各模块依赖的功能
+    /// </summary>
+    public class Mediator : AbstractMediator
+    {
+        public override int GetBuyRequirement()
+        {
+            return base.HomeBuyer.GetRequirement();
+        }
+
+        public override int GetCurrentHouseNumber()
+        {
+            return base.HouseBuilder.ShowHouseNum();
+        }
+
+        public override string GetRule()
+        {
+            return base.ControlCenter.ShowRule();
+        }
+    }
+}

+ 59 - 0
MediatorPattern/MediatorPattern.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>{EA608B4B-5203-42F6-891D-59BEB23F3B38}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>MediatorPattern</RootNamespace>
+    <AssemblyName>MediatorPattern</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="Mediator.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>

+ 44 - 0
MediatorPattern/Program.cs

@@ -0,0 +1,44 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace MediatorPattern
+{
+    class Program
+    {
+        static void Main(string[] args)
+        {
+            AbstractMediator mediator = new Mediator();
+
+            //声明参与的角色
+            HomeBuyer buyer = new HomeBuyer(mediator);
+            Builder build = new Builder(mediator);
+            ControlCenter center = new ControlCenter(mediator);
+
+            //将需要的角色注入到中介
+            mediator.HouseBuilder = build;
+            mediator.HomeBuyer = buyer;
+            mediator.ControlCenter = center;
+
+            int initRequirement = mediator.GetBuyRequirement();
+            int initHousenum = mediator.GetCurrentHouseNumber();
+
+            Console.WriteLine(string.Format("目前购房需求为:{0}套;现有房源:{1}套。", initRequirement, initHousenum));
+
+            //买房300套
+            buyer.BuyHouse(300);
+            
+            build.SaleHouse(300);            
+
+            //国家住建局,考察市场
+            center.Limit();
+
+            //再买房1000套
+            buyer.BuyHouse(1000);
+
+            Console.ReadLine();
+        }
+    }
+}

+ 36 - 0
MediatorPattern/Properties/AssemblyInfo.cs

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