瀏覽代碼

组合模式

jeffrey 8 年之前
父節點
當前提交
16d57c3242

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

+ 61 - 0
CompositePattern/CompositePattern.csproj

@@ -0,0 +1,61 @@
+<?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>{EDEE3E18-5C3F-4B91-9EDF-393DC42F5E3F}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>CompositePattern</RootNamespace>
+    <AssemblyName>CompositePattern</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="Organization.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>

+ 73 - 0
CompositePattern/Organization.cs

@@ -0,0 +1,73 @@
+using System;
+using System.Collections.Generic;
+
+namespace CompositePattern
+{
+    /// <summary>
+    ///     组织架构
+    /// </summary>
+    public abstract class Organization
+    {
+        /// <summary>
+        ///     成员姓名
+        /// </summary>
+        public string MemberName { get; set; }
+
+        /// <summary>
+        ///     成员职位
+        /// </summary>
+        public string MemberPosition { get; set; }
+
+        /// <summary>
+        ///     直接上级
+        /// </summary>
+        public Organization ParentNode { get; set; }
+
+        public void Display()
+        {
+            var basicInfo = string.Format("姓名:{0},职位:{1}", MemberName, MemberPosition);
+            var parentInfo = ParentNode == null
+                ? ""
+                : string.Format(",直接上级:『姓名:{0},职位:{1}』", ParentNode.MemberName, ParentNode.MemberPosition);
+            Console.WriteLine(basicInfo + parentInfo);
+        }
+    }
+
+    /// <summary>
+    ///     部门
+    /// </summary>
+    public class Department : Organization
+    {
+        private readonly List<Organization> _organizationInfo = new List<Organization>();
+
+        public Department(string departmentName, string charge)
+        {
+            MemberPosition = departmentName;
+            MemberName = charge;
+        }
+
+        public void Add(Organization org)
+        {
+            _organizationInfo.Add(org);
+            org.ParentNode = this;
+        }
+
+        public void Remove(Organization org)
+        {
+            _organizationInfo.Remove(org);
+        }
+
+        public List<Organization> GetDepartmentMembers()
+        {
+            return _organizationInfo;
+        }
+    }
+
+
+    /// <summary>
+    ///     员工
+    /// </summary>
+    public class Member : Organization
+    {
+    }
+}

+ 73 - 0
CompositePattern/Program.cs

@@ -0,0 +1,73 @@
+using System;
+
+namespace CompositePattern
+{
+    internal class Program
+    {
+        private static void Main(string[] args)
+        {
+            Console.WriteLine("组合模式:");
+            Console.WriteLine("-------------------");
+
+            var organzation = new Department("CEO", "老总");
+            var developDepart = new Department("研发部经理", "研哥");
+
+            organzation.Add(developDepart);
+
+            var projectA = new Department("Erp项目组长", "E哥");
+
+            developDepart.Add(projectA);
+
+            var memberX = new Member {MemberPosition = "开发工程师", MemberName = "开发X"};
+            var memberY = new Member {MemberPosition = "开发工程师", MemberName = "开发Y"};
+            var memberZ = new Member {MemberPosition = "测试工程师", MemberName = "测试Z"};
+
+            projectA.Add(memberX);
+            projectA.Add(memberY);
+            projectA.Add(memberZ);
+
+            Console.WriteLine("组合模式:从上往下遍历");
+            DisplayStructure(organzation);
+            Console.WriteLine("-------------------");
+            Console.WriteLine();
+
+            Console.WriteLine("组合模式:从下往上遍历");
+            FindParent(memberX);
+            Console.WriteLine("-------------------");
+            Console.ReadLine();
+        }
+
+        /// <summary>
+        ///     正序排序
+        /// </summary>
+        /// <param name="org"></param>
+        private static void DisplayStructure(Organization org)
+        {
+            if (org.ParentNode == null)
+                org.Display();
+
+            var departMent = (Department) org;
+
+            foreach (var depart in departMent.GetDepartmentMembers())
+            {
+                depart.Display();
+                if (!(depart is Member))
+                    DisplayStructure((Department) depart);
+            }
+        }
+
+        /// <summary>
+        ///     倒序排序
+        /// </summary>
+        /// <param name="member"></param>
+        private static void FindParent(Organization member)
+        {
+            member.Display();
+            while (member.ParentNode != null)
+            {
+                member.ParentNode.Display();
+                member = member.ParentNode;
+            }
+        }
+    }
+}

+ 36 - 0
CompositePattern/Properties/AssemblyInfo.cs

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

+ 6 - 0
DesignPattern.sln

@@ -27,6 +27,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StrategyPattern", "Strategy
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdapterPattern", "AdapterPattern\AdapterPattern.csproj", "{A0D5F127-471C-47AC-A9E0-F2BB72D2EF8F}"
 EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompositePattern", "CompositePattern\CompositePattern.csproj", "{EDEE3E18-5C3F-4B91-9EDF-393DC42F5E3F}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -81,6 +83,10 @@ Global
 		{A0D5F127-471C-47AC-A9E0-F2BB72D2EF8F}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{A0D5F127-471C-47AC-A9E0-F2BB72D2EF8F}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{A0D5F127-471C-47AC-A9E0-F2BB72D2EF8F}.Release|Any CPU.Build.0 = Release|Any CPU
+		{EDEE3E18-5C3F-4B91-9EDF-393DC42F5E3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{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
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE