Browse Source

Add project files.

shengjie_yan 9 years ago
parent
commit
2ec6e517ef

+ 22 - 0
DesignPattern.sln

@@ -0,0 +1,22 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 14
+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
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Release|Any CPU = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{B6F92CD5-5347-4F36-96CB-2ED8B9F66C25}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{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
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal

+ 32 - 0
FactoryPattern/AbstractBus.cs

@@ -0,0 +1,32 @@
+using System;
+
+namespace FactoryPattern
+{
+    public abstract class AbstractBus
+    {
+        protected abstract void DoOperation();
+
+        public void GetInfo()
+        {
+            Console.WriteLine($"I am {this.GetType().Name}.");
+        }
+    }
+
+    public class ConcreateBusA : AbstractBus
+    {
+
+        protected override void DoOperation()
+        {
+
+            throw new System.NotImplementedException();
+        }
+    }
+
+    public class ConcreateBusB : AbstractBus
+    {
+        protected override void DoOperation()
+        {
+            throw new System.NotImplementedException();
+        }
+    }
+}

+ 36 - 0
FactoryPattern/AbstractCar.cs

@@ -0,0 +1,36 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace FactoryPattern
+{
+    public abstract class AbstractCar
+    {
+        protected abstract void DoOperation();
+
+        public void GetInfo()
+        {
+            Console.WriteLine($"I am {this.GetType().Name}.");
+        }
+    }
+
+    public class ConcreateCarA : AbstractCar
+    {
+
+        protected override void DoOperation()
+        {
+            
+            throw new System.NotImplementedException();
+        }
+    }
+
+    public class ConcreateCarB : AbstractCar
+    {
+        protected override void DoOperation()
+        {
+            throw new System.NotImplementedException();
+        }
+    }
+}

+ 51 - 0
FactoryPattern/AbstractFactory.cs

@@ -0,0 +1,51 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace FactoryPattern
+{
+    /// <summary>
+    /// 抽象工厂模式:
+    /// 抽象工厂是应对产品族概念的,比如说,每个汽车公司可能要同时生产轿车,货车,客车,那么每一个工厂都要有创建轿车,货车和客车的方法。
+    /// 应对产品族概念而生,增加新的产品线很容易,但是无法增加新的产品。
+    /// </summary>
+    public interface IAbstractFactory
+    {
+        AbstractCar CreateCar();
+        AbstractBus CreateBus();
+    }
+
+    /// <summary>
+    /// 宝马工厂
+    /// </summary>
+    public class BMWFactory:IAbstractFactory
+    {
+        public AbstractCar CreateCar()
+        {
+            return new ConcreateCarA();
+        }
+
+        public AbstractBus CreateBus()
+        {
+            return new ConcreateBusA();
+        }
+    }
+
+    /// <summary>
+    /// 比亚迪工厂
+    /// </summary>
+    public class BYDFactory : IAbstractFactory
+    {
+        public AbstractCar CreateCar()
+        {
+            return new ConcreateCarB();
+        }
+
+        public AbstractBus CreateBus()
+        {
+            return new ConcreateBusB();
+        }
+    }
+}

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

+ 66 - 0
FactoryPattern/FactoryPattern.csproj

@@ -0,0 +1,66 @@
+<?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>{B6F92CD5-5347-4F36-96CB-2ED8B9F66C25}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>FactoryPattern</RootNamespace>
+    <AssemblyName>FactoryPattern</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="AbstractBus.cs" />
+    <Compile Include="AbstractFactory.cs" />
+    <Compile Include="AbstractCar.cs" />
+    <Compile Include="IFactoryMethod.cs" />
+    <Compile Include="Program.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="ReflectFactory.cs" />
+    <Compile Include="SimpleFactory.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>

+ 29 - 0
FactoryPattern/IFactoryMethod.cs

@@ -0,0 +1,29 @@
+namespace FactoryPattern
+{
+    /// <summary>
+    /// 工厂方法模式:
+    /// 工厂方法是针对每一种产品提供一个工厂类。通过不同的工厂实例来创建不同的产品实例。
+    /// 在同一等级结构中,支持增加任意产品。
+    /// 符合【开放封闭原则】,但随着产品类的增加,对应的工厂也会随之增多
+    /// </summary>
+    public interface IFactoryMethod
+    {
+        AbstractCar Create();
+    }
+
+    public class ConcreateFactoryA:IFactoryMethod
+    {
+        public AbstractCar Create()
+        {
+            return new ConcreateCarA();
+        }
+    }
+
+    public class ConcreateFactoryB : IFactoryMethod
+    {
+        public AbstractCar Create()
+        {
+            return new ConcreateCarB();
+        }
+    }
+}

+ 80 - 0
FactoryPattern/Program.cs

@@ -0,0 +1,80 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace FactoryPattern
+{
+    class Program
+    {
+        //简单工厂:简单实用,但违反开放封闭;
+        //工厂方法:开放封闭,单一产品;
+        //抽象工厂:开放封闭,多个产品;
+        //反射工厂:可以最大限度的解耦。 
+        static void Main(string[] args)
+        {
+            TestSimpleFactory();
+            TestFactoryMethod();
+            TestReflectFactory();
+            TestAbstractFactory();
+        }
+
+        /// <summary>
+        /// 测试简单工厂模式
+        /// </summary>
+        private static void TestSimpleFactory()
+        {
+            Console.WriteLine("简单工厂模式:");
+            var productA = SimpleFactory.Create(ProductEnum.ConcreateProductA);
+            productA.GetInfo();
+            Console.ReadLine();
+        }
+
+        /// <summary>
+        /// 测试工厂方法模式
+        /// </summary>
+        private static void TestFactoryMethod()
+        {
+            Console.WriteLine("工厂方法模式:");
+            IFactoryMethod factoryB =new ConcreateFactoryB();
+            var productB = factoryB.Create();
+            productB.GetInfo();
+
+            Console.ReadLine();
+        }
+
+        /// <summary>
+        /// 测试反射工厂模式
+        /// </summary>
+        private static void TestReflectFactory()
+        {
+            Console.WriteLine("反射工厂模式:");
+            var productB = ReflectFactory.Create("FactoryPattern.ConcreateCarB");
+
+            productB.GetInfo();
+            Console.ReadLine();
+        }
+
+        /// <summary>
+        /// 测试抽象工厂模式
+        /// </summary>
+        private static void TestAbstractFactory()
+        {
+            Console.WriteLine("抽象工厂模式:");
+
+            var bmwFactory = new BMWFactory();
+            bmwFactory.CreateCar().GetInfo();
+            bmwFactory.CreateBus().GetInfo();
+
+            var bydFactory = new BYDFactory();
+            bydFactory.CreateCar().GetInfo();
+            bydFactory.CreateBus().GetInfo();
+
+            Console.ReadLine();
+        }
+
+
+    }
+}

+ 36 - 0
FactoryPattern/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("FactoryPattern")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("FactoryPattern")]
+[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("b6f92cd5-5347-4f36-96cb-2ed8b9f66c25")]
+
+// 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")]

+ 23 - 0
FactoryPattern/ReflectFactory.cs

@@ -0,0 +1,23 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace FactoryPattern
+{
+    /// <summary>
+    /// 反射工厂模式
+    /// 是针对简单工厂模式的一种改进
+    /// </summary>
+    public static class ReflectFactory
+    {
+        public static AbstractCar Create(string typeName)
+        {
+            Type type = Type.GetType(typeName, true, true);
+            var instance = type?.Assembly.CreateInstance(typeName) as AbstractCar;
+
+            return instance;
+        }
+    }
+}

+ 30 - 0
FactoryPattern/SimpleFactory.cs

@@ -0,0 +1,30 @@
+namespace FactoryPattern
+{
+    public enum ProductEnum
+    {
+        ConcreateProductA,
+        ConcreateProductB
+    }
+
+    /// <summary>
+    /// 简单工厂模式:
+    /// 简单工厂模式的工厂类一般是使用静态方法,通过接收的参数的不同来返回不同的对象实例。
+    /// 不修改代码的话,是无法扩展的。(如果增加新的产品,需要增加工厂的Swith分支)
+    /// 不符合【开放封闭原则】
+    /// </summary>
+    public static class SimpleFactory
+    {
+        public static AbstractCar Create(ProductEnum productType)
+        {
+            switch (productType)
+            {
+                case ProductEnum.ConcreateProductA:
+                    return new ConcreateCarA();
+                case ProductEnum.ConcreateProductB:
+                    return new ConcreateCarB();
+                default:
+                    return null;
+            }
+        }
+    }
+}