shengjie_yan 8 vuotta sitten
vanhempi
sitoutus
7914d05937

+ 6 - 0
DesignPattern.sln

@@ -35,6 +35,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FacadePattern", "FacadePatt
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MementoPattern", "MementoPattern\MementoPattern.csproj", "{075919B3-9370-4DCE-9B16-ED0EDEC53735}"
 EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IteratorPattern", "IteratorPattern\IteratorPattern.csproj", "{04898517-CD60-419B-9C4D-2BE8A99C40FC}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -105,6 +107,10 @@ Global
 		{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
+		{04898517-CD60-419B-9C4D-2BE8A99C40FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{04898517-CD60-419B-9C4D-2BE8A99C40FC}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{04898517-CD60-419B-9C4D-2BE8A99C40FC}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{04898517-CD60-419B-9C4D-2BE8A99C40FC}.Release|Any CPU.Build.0 = Release|Any CPU
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

+ 80 - 6
FacadePattern/ATM.cs

@@ -1,12 +1,86 @@
 using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
 
 namespace FacadePattern
 {
-    class ATM
+    public class ATM
     {
+        public void DisplayUi()
+        {
+            var facade = new AtmFacade();
+
+            while (true)
+                try
+                {
+                    if (!facade.IsLogin())
+                    {
+                        Console.WriteLine("请输入银行卡号:");
+                        var bkNo = Console.ReadLine();
+                        Console.WriteLine("请输入密码:");
+                        var pwd = Console.ReadLine();
+                        facade.Login(bkNo, pwd);
+                    }
+                    else
+                    {
+                        ShowBusiness(facade);
+                    }
+                }
+                catch (Exception ex)
+                {
+                    Console.ForegroundColor = ConsoleColor.Red;
+                    Console.WriteLine(ex.Message);
+                    Console.ResetColor();
+                }
+        }
+
+
+        private static void ShowBusiness(AtmFacade facade)
+        {
+            Console.WriteLine("==========================================");
+            Console.WriteLine("欢迎你!请选择服务项目:");
+            Console.WriteLine("1、取款");
+            Console.WriteLine("2、存款");
+            Console.WriteLine("3、转账");
+            Console.WriteLine("4、查询余额");
+            Console.WriteLine("5、清屏");
+            Console.WriteLine("==========================================");
+
+            var pressKey = Console.ReadKey();
+
+            switch (pressKey.Key)
+            {
+                case ConsoleKey.D1:
+                    Console.WriteLine();
+                    Console.WriteLine("请输入取款金额:");
+                    var money = Convert.ToInt32(Console.ReadLine());
+                    facade.WithdrewCash(money);
+                    break;
+                case ConsoleKey.D2:
+                    Console.WriteLine();
+                    Console.WriteLine("请输入存款金额:");
+                    var depositNum = Convert.ToInt32(Console.ReadLine());
+                    facade.DepositCash(depositNum);
+                    break;
+                case ConsoleKey.D3:
+                    Console.WriteLine();
+                    Console.WriteLine("请输入目标账号:");
+                    var targetNo = Console.ReadLine();
+                    Console.WriteLine("请输入转账金额:");
+                    var transferNum = Convert.ToInt32(Console.ReadLine());
+                    facade.TransferMoney(targetNo, transferNum);
+                    break;
+                case ConsoleKey.D4:
+                    Console.WriteLine();
+                    facade.QueryBalance();
+                    break;
+                case ConsoleKey.D5:
+                    Console.Clear();
+                    break;
+                default:
+                    Console.ForegroundColor = ConsoleColor.Red;
+                    Console.WriteLine("输入有误,请重新输入");
+                    Console.ResetColor();
+                    break;
+            }
+        }
     }
-}
+}

+ 55 - 0
FacadePattern/AccountSubsystem.cs

@@ -0,0 +1,55 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace FacadePattern
+{
+    /// <summary>
+    /// 账户管理子系统
+    /// </summary>
+    public static class AccountSubsystem
+    {
+        private static readonly List<BankAccount> Accounts = new List<BankAccount>
+        {
+            new BankAccount("123455", "555555", "圣杰", "138****9309", 1000000),
+            new BankAccount("123454", "444444", "产品汪", "157****9309", 2000000),
+            new BankAccount("123453", "333333", "运营喵", "154****9309", 3000000),
+            new BankAccount("123452", "222222", "程序猿", "187****9309", 4000000),
+            new BankAccount("123451", "111111", "设计狮", "189****9309", 5000000)
+        };
+
+        public static BankAccount Login(string bankNo, string password)
+        {
+            var bankAccount = Accounts.FirstOrDefault(a => a.BankNo == bankNo);
+            if (bankAccount == null)
+                throw new Exception("无效卡号!!!");
+
+            if (bankAccount.Password != password)
+                throw new Exception("密码错误!!!");
+
+            return bankAccount;
+        }
+
+        public static BankAccount GetAccount(string bankNo)
+        {
+            var bankAccount = Accounts.FirstOrDefault(a => a.BankNo == bankNo);
+            if (bankAccount == null)
+                throw new Exception("无效卡号!!!");
+
+
+            return bankAccount;
+        }
+
+        public static void Display(BankAccount account)
+        {
+            Console.WriteLine("卡号:{0},持卡人姓名:{1},手机号:{2},余额:{3}", account.BankNo, account.Name, account.Phone,
+                account.TotalMoney);
+        }
+
+
+        public static bool ChangePassword()
+        {
+            throw new NotImplementedException();
+        }
+    }
+}

+ 0 - 23
FacadePattern/AccountVerificationCenter.cs

@@ -1,23 +0,0 @@
-using System.Collections.Generic;
-
-namespace FacadePattern
-{
-    /// <summary>
-    ///     银行账户验证中心
-    /// </summary>
-    public class AccountVerificationCenter
-    {
-        private readonly List<BankAccount> accounts = new List<BankAccount>
-        {
-            new BankAccount("123456789012345", "555555", "圣杰", "135****9309", 1000000),
-            new BankAccount("123456789012346", "222222", "Jeffrey", "135****9309", 2000000),
-            new BankAccount("123456789012347", "333333", "Shengjie", "135****9309", 3000000),
-            new BankAccount("123456789012348", "777777", "程序猿", "135****9309", 4000000),
-            new BankAccount("123456789012349", "888888", "设计狮", "135****9309", 5000000)
-        };
-
-        public void Verify(string bankNo, string password)
-        {
-        }
-    }
-}

+ 72 - 0
FacadePattern/AtmFacade.cs

@@ -0,0 +1,72 @@
+using System;
+
+namespace FacadePattern
+{
+    /// <summary>
+    ///     ATM机专属门面
+    /// </summary>
+    public class AtmFacade
+    {
+        private readonly IBankSubsystem _bankSubsystem = new BankSubsystem();
+        private BankAccount _account;
+
+        public void Login(string no, string pwd)
+        {
+            _account = AccountSubsystem.Login(no, pwd);
+        }
+
+        public bool IsLogin()
+        {
+            return _account != null;
+        }
+
+        /// <summary>
+        ///     取款
+        /// </summary>
+        /// <param name="money"></param>
+        public void WithdrewCash(int money)
+        {
+            if (_bankSubsystem.WithdrewMoney(_account, money))
+            {
+                Console.WriteLine("取款成功!");
+                AccountSubsystem.Display(_account);
+            }
+        }
+
+        /// <summary>
+        ///     存款
+        /// </summary>
+        /// <param name="money"></param>
+        public void DepositCash(int money)
+        {
+            if (_bankSubsystem.DepositMoney(_account, money))
+            {
+                Console.WriteLine("存款成功!");
+                AccountSubsystem.Display(_account);
+            }
+        }
+
+        /// <summary>
+        ///     查余额
+        /// </summary>
+        public void QueryBalance()
+        {
+            if (_bankSubsystem.CheckBalance(_account) > 0)
+                AccountSubsystem.Display(_account);
+        }
+
+        /// <summary>
+        ///     转账
+        /// </summary>
+        /// <param name="targetNo"></param>
+        /// <param name="money"></param>
+        public void TransferMoney(string targetNo, int money)
+        {
+            if (_bankSubsystem.TransferMoney(_account, targetNo, money))
+            {
+                Console.WriteLine("转账成功!");
+                AccountSubsystem.Display(_account);
+            }
+        }
+    }
+}

+ 0 - 32
FacadePattern/Bank.cs

@@ -1,32 +0,0 @@
-using System;
-
-namespace FacadePattern
-{
-    public class Bank : IBank
-    {
-        /// <summary>
-        ///     查询余额
-        /// </summary>
-        /// <param name="account">银行账户</param>
-        /// <returns></returns>
-        public int CheckBalance(BankAccount account)
-        {
-            throw new NotImplementedException();
-        }
-
-        public int WithdrewMoney(BankAccount account, int money)
-        {
-            throw new NotImplementedException();
-        }
-
-        public int DepositMoney(BankAccount account, int money)
-        {
-            throw new NotImplementedException();
-        }
-
-        public int TransferMoney(BankAccount account, BankAccount targetAccount, int money)
-        {
-            throw new NotImplementedException();
-        }
-    }
-}

+ 80 - 0
FacadePattern/BankSubsystem.cs

@@ -0,0 +1,80 @@
+using System;
+
+namespace FacadePattern
+{
+    public class BankSubsystem : IBankSubsystem
+    {
+        /// <summary>
+        ///     查询余额
+        /// </summary>
+        /// <param name="account">银行账户</param>
+        /// <returns></returns>
+        public int CheckBalance(BankAccount account)
+        {
+            return account.TotalMoney;
+        }
+
+        /// <summary>
+        ///     取款
+        /// </summary>
+        /// <param name="account">银行账户</param>
+        /// <param name="money">取多少钱</param>
+        /// <returns>余额</returns>
+        public bool WithdrewMoney(BankAccount account, int money)
+        {
+            if (account.TotalMoney >= money)
+                account.TotalMoney -= money;
+            else
+                throw new Exception("余额不足!");
+
+            return true;
+        }
+
+        /// <summary>
+        ///     转账
+        /// </summary>
+        /// <param name="account">转出账户</param>
+        /// <param name="targetNo">目标账户</param>
+        /// <param name="money">转多少钱</param>
+        /// <returns></returns>
+        public bool TransferMoney(BankAccount account, string targetNo, int money)
+        {
+            var targetAccount = AccountSubsystem.GetAccount(targetNo);
+
+            if (targetAccount == null)
+                throw new Exception("目标账户不存在!");
+
+            if (account.TotalMoney < money)
+                throw new Exception("余额不足!");
+
+            account.TotalMoney -= money;
+            targetAccount.TotalMoney += money;
+
+            return true;
+        }
+
+        /// <summary>
+        ///     存款
+        /// </summary>
+        /// <param name="account">银行账户</param>
+        /// <param name="money">存多少钱</param>
+        /// <returns></returns>
+        public bool DepositMoney(BankAccount account, int money)
+        {
+            account.TotalMoney += money;
+            return true;
+        }
+
+        /// <summary>
+        ///     充值话费
+        /// </summary>
+        /// <param name="phoneNumber">手机号</param>
+        /// <param name="account">银行账户</param>
+        /// <param name="money">充值多少</param>
+        /// <returns></returns>
+        public bool RechargeMobilePhone(BankAccount account, string phoneNumber, int money)
+        {
+            throw new NotImplementedException();
+        }
+    }
+}

+ 4 - 3
FacadePattern/FacadePattern.csproj

@@ -43,11 +43,12 @@
     <Reference Include="System.Xml" />
   </ItemGroup>
   <ItemGroup>
-    <Compile Include="AccountVerificationCenter.cs" />
+    <Compile Include="AccountSubsystem.cs" />
     <Compile Include="ATM.cs" />
-    <Compile Include="Bank.cs" />
+    <Compile Include="AtmFacade.cs" />
+    <Compile Include="BankSubsystem.cs" />
     <Compile Include="BankAccount.cs" />
-    <Compile Include="IBank.cs" />
+    <Compile Include="IBankSubsystem.cs" />
     <Compile Include="Program.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
   </ItemGroup>

+ 17 - 5
FacadePattern/IBank.cs → FacadePattern/IBankSubsystem.cs

@@ -1,6 +1,9 @@
 namespace FacadePattern
 {
-    public interface IBank
+    /// <summary>
+    ///     银行现金业务子系统
+    /// </summary>
+    public interface IBankSubsystem
     {
         /// <summary>
         ///     查询余额
@@ -15,7 +18,7 @@
         /// <param name="account">银行账户</param>
         /// <param name="money">取多少钱</param>
         /// <returns></returns>
-        int WithdrewMoney(BankAccount account, int money);
+        bool WithdrewMoney(BankAccount account, int money);
 
         /// <summary>
         ///     存款
@@ -23,15 +26,24 @@
         /// <param name="account">银行账户</param>
         /// <param name="money">存多少钱</param>
         /// <returns></returns>
-        int DepositMoney(BankAccount account, int money);
+        bool DepositMoney(BankAccount account, int money);
 
         /// <summary>
         ///     转账
         /// </summary>
         /// <param name="account">转出账户</param>
-        /// <param name="targetAccount">目标账户</param>
+        /// <param name="targetNo">目标账户</param>
         /// <param name="money">转多少钱</param>
         /// <returns></returns>
-        int TransferMoney(BankAccount account, BankAccount targetAccount, int money);
+        bool TransferMoney(BankAccount account, string targetNo, int money);
+
+        /// <summary>
+        ///     充值话费
+        /// </summary>
+        /// <param name="phoneNumber">手机号</param>
+        /// <param name="account">银行账户</param>
+        /// <param name="money">充值多少</param>
+        /// <returns></returns>
+        bool RechargeMobilePhone(BankAccount account, string phoneNumber, int money);
     }
 }

+ 6 - 10
FacadePattern/Program.cs

@@ -1,15 +1,11 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace FacadePattern
+namespace FacadePattern
 {
-    class Program
+    internal class Program
     {
-        static void Main(string[] args)
+        private static void Main(string[] args)
         {
+            var atm = new ATM();
+            atm.DisplayUi();
         }
     }
-}
+}

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

+ 91 - 0
IteratorPattern/Iterator.cs

@@ -0,0 +1,91 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace IteratorPattern
+{
+    // 抽象聚合类
+    public interface IListCollection
+    {
+        Iterator GetIterator();
+    }
+
+    // 迭代器抽象类
+    public interface Iterator
+    {
+        bool MoveNext();
+        Object GetCurrent();
+        void Next();
+        void Reset();
+    }
+
+    // 具体聚合类
+    public class ConcreteList : IListCollection
+    {
+        readonly string[] _collection;
+        public ConcreteList()
+        {
+            _collection = new string[] { "A", "B", "C", "D" };
+        }
+
+        public Iterator GetIterator()
+        {
+            return new ConcreteIterator(this);
+        }
+
+        public int Length
+        {
+            get { return _collection.Length; }
+        }
+
+        public string GetElement(int index)
+        {
+            return _collection[index];
+        }
+    }
+
+    // 具体迭代器类
+    public class ConcreteIterator : Iterator
+    {
+        // 迭代器要集合对象进行遍历操作,自然就需要引用集合对象
+        private ConcreteList _list;
+        private int _index;
+
+        public ConcreteIterator(ConcreteList list)
+        {
+            _list = list;
+            _index = 0;
+        }
+
+        public bool MoveNext()
+        {
+            if (_index < _list.Length)
+            {
+                return true;
+            }
+            return false;
+        }
+
+        public Object GetCurrent()
+        {
+            return _list.GetElement(_index);
+        }
+
+        public void Reset()
+        {
+            _index = 0;
+        }
+
+        public void Next()
+        {
+            if (_index < _list.Length)
+            {
+                _index++;
+            }
+
+        }
+    }
+    
+}

+ 61 - 0
IteratorPattern/IteratorPattern.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>{04898517-CD60-419B-9C4D-2BE8A99C40FC}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>IteratorPattern</RootNamespace>
+    <AssemblyName>IteratorPattern</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="Iterator.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>

+ 27 - 0
IteratorPattern/Program.cs

@@ -0,0 +1,27 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace IteratorPattern
+{
+    class Program
+    {
+        static void Main(string[] args)
+        {
+            Console.WriteLine("迭代器模式:");
+            IListCollection list = new ConcreteList();
+            var iterator = list.GetIterator();
+
+            while (iterator.MoveNext())
+            {
+                int i = (int)iterator.GetCurrent();
+                Console.WriteLine(i.ToString());
+                iterator.Next();
+            }
+
+            Console.Read();
+        }
+    }
+}

+ 36 - 0
IteratorPattern/Properties/AssemblyInfo.cs

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

+ 3 - 1
README.md

@@ -1,4 +1,4 @@
-# 『设计模式』之小试牛刀
+# 『设计模式』之小试牛刀(来了就给个Star吧!)
 <blockquote>
 为了更好的学习设计模式,以及督促自己完成设计模式的学习,现提笔为记。
 怎么的,每周至少也要学一个设计模式!!!
@@ -47,4 +47,6 @@
 
 17. [『观察者模式』来钓鱼](http://www.jianshu.com/p/45675c73296d)
 
+18. [ATM取款聊聊『门面模式』](http://www.jianshu.com/p/c89a922a60c0)
+
 ![设计模式之禅](http://upload-images.jianshu.io/upload_images/2799767-4df489c0f630a241.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)