瀏覽代碼

备忘录模式

shengjie_yan 8 年之前
父節點
當前提交
9d01c631c6

+ 6 - 0
DesignPattern.sln

@@ -33,6 +33,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ObserverPattern", "Observer
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FacadePattern", "FacadePattern\FacadePattern.csproj", "{CA00E48A-FCA2-44F1-A7C3-DF89FD3802BE}"
 EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MementoPattern", "MementoPattern\MementoPattern.csproj", "{075919B3-9370-4DCE-9B16-ED0EDEC53735}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -99,6 +101,10 @@ Global
 		{CA00E48A-FCA2-44F1-A7C3-DF89FD3802BE}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{CA00E48A-FCA2-44F1-A7C3-DF89FD3802BE}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{CA00E48A-FCA2-44F1-A7C3-DF89FD3802BE}.Release|Any CPU.Build.0 = Release|Any CPU
+		{075919B3-9370-4DCE-9B16-ED0EDEC53735}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{075919B3-9370-4DCE-9B16-ED0EDEC53735}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{075919B3-9370-4DCE-9B16-ED0EDEC53735}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{075919B3-9370-4DCE-9B16-ED0EDEC53735}.Release|Any CPU.Build.0 = Release|Any CPU
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

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

+ 17 - 0
MementoPattern/Caretaker.cs

@@ -0,0 +1,17 @@
+using System.Collections.Generic;
+
+namespace MementoPattern
+{
+    /// <summary>
+    /// 备忘录管理
+    /// </summary>
+    public class Caretaker
+    {
+        // 存储多个备份
+        public Dictionary<string, ContactMemento> ContactMementoes { get; set; }
+        public Caretaker()
+        {
+            ContactMementoes = new Dictionary<string, ContactMemento>();
+        }
+    }
+}

+ 26 - 0
MementoPattern/ContactMemento.cs

@@ -0,0 +1,26 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace MementoPattern
+{
+    /// <summary>
+    /// 备忘录
+    /// </summary>
+    public class ContactMemento
+    {
+        private readonly List<ContactPerson> _backupContactPersons;
+
+        public List<ContactPerson> GetMemento()
+        {
+            return _backupContactPersons;
+        }
+
+        public ContactMemento(List<ContactPerson> backupContactPersons)
+        {
+            _backupContactPersons = backupContactPersons;
+        }
+    }
+}

+ 24 - 0
MementoPattern/ContactPerson.cs

@@ -0,0 +1,24 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace MementoPattern
+{
+    /// <summary>
+    /// 联系人
+    /// </summary>
+    public class ContactPerson
+    {
+        public string Name { get; set; }
+
+        public string PhoneNumber { get; set; }
+
+        public ContactPerson(string name, string phoneNumber)
+        {
+            Name = name;
+            PhoneNumber = phoneNumber;
+        }
+    }
+}

+ 64 - 0
MementoPattern/MementoPattern.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>{075919B3-9370-4DCE-9B16-ED0EDEC53735}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>MementoPattern</RootNamespace>
+    <AssemblyName>MementoPattern</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="Caretaker.cs" />
+    <Compile Include="ContactMemento.cs" />
+    <Compile Include="ContactPerson.cs" />
+    <Compile Include="Mobile.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>

+ 54 - 0
MementoPattern/Mobile.cs

@@ -0,0 +1,54 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace MementoPattern
+{
+    /// <summary>
+    /// 手机用户
+    /// </summary>
+    public class Mobile
+    {
+        private List<ContactPerson> _contactPersons;
+
+        public List<ContactPerson> GetPhoneBook()
+        {
+            return _contactPersons;
+        }
+
+        public Mobile(List<ContactPerson> contactPersons)
+        {
+            _contactPersons = contactPersons;
+        }
+
+        /// <summary>
+        /// 创建备份
+        /// </summary>
+        /// <returns></returns>
+        public ContactMemento CreateMemento()
+        {
+            //思考以下为什么要new List<ContactPerson>(_contactPersons)
+            return new ContactMemento(new List<ContactPerson>(_contactPersons));
+        }
+
+        /// <summary>
+        /// 恢复备份
+        /// </summary>
+        /// <param name="memento"></param>
+        public void RestoreMemento(ContactMemento memento)
+        {
+            this._contactPersons = memento.GetMemento();
+        }
+
+        public void DisplayPhoneBook()
+        {
+            Console.WriteLine($"共有{_contactPersons.Count}位联系人,联系人列表如下:");
+            foreach (var contactPerson in _contactPersons)
+            {
+                Console.WriteLine($"姓名:{contactPerson.Name},电话:{contactPerson.PhoneNumber}");
+            }
+        }
+    }
+}

+ 60 - 0
MementoPattern/Program.cs

@@ -0,0 +1,60 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace MementoPattern
+{
+    class Program
+    {
+        static void Main(string[] args)
+        {
+            Console.WriteLine("======备忘录模式======");
+
+            List<ContactPerson> persons = new List<ContactPerson>()
+            {
+                new ContactPerson("张三","13513757890"),
+                new ContactPerson("李四","18563252369"),
+                new ContactPerson("王二","17825635486"),
+            };
+
+            Mobile mobile = new Mobile(persons);
+
+            mobile.DisplayPhoneBook();
+
+            //备份通讯录
+            Console.WriteLine("===通讯录已备份===");
+            Caretaker caretaker = new Caretaker();
+            string key = DateTime.Now.ToString(CultureInfo.InvariantCulture);
+            caretaker.ContactMementoes.Add(DateTime.Now.ToString(CultureInfo.InvariantCulture), mobile.CreateMemento());
+            Console.WriteLine($"==={key}:通讯录已备份===");
+
+            //移除第一个联系人
+            Console.WriteLine("----移除联系人----");
+            mobile.GetPhoneBook().RemoveAt(0);
+            mobile.DisplayPhoneBook();
+
+            Thread.Sleep(2000);
+            string key2 = DateTime.Now.ToString(CultureInfo.InvariantCulture);
+            caretaker.ContactMementoes.Add(DateTime.Now.ToString(CultureInfo.InvariantCulture), mobile.CreateMemento());
+            Console.WriteLine($"==={key2}:通讯录已备份===");
+
+            //再移除一个联系人
+            Console.WriteLine("----移除联系人----");
+            mobile.GetPhoneBook().RemoveAt(0);
+            mobile.DisplayPhoneBook();
+
+            //恢复通讯录
+            Console.WriteLine($"----恢复到最后一次通讯录备份:{caretaker.ContactMementoes.LastOrDefault().Key}----");
+            mobile.RestoreMemento(caretaker.ContactMementoes.LastOrDefault().Value);
+
+            mobile.DisplayPhoneBook();
+
+            Console.ReadLine();
+
+        }
+    }
+}

+ 36 - 0
MementoPattern/Properties/AssemblyInfo.cs

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