state pattern (vending machine example)

remotes/origin/master
syneffort 3 years ago
parent d8ab3a9247
commit 529a15d5f8
  1. 6
      DesignPattern/DesignPattern.sln
  2. 6
      DesignPattern/State-VendingMachineExample/App.config
  3. 21
      DesignPattern/State-VendingMachineExample/Client.cs
  4. 38
      DesignPattern/State-VendingMachineExample/DispenseChangeState.cs
  5. 39
      DesignPattern/State-VendingMachineExample/DispenseItemState.cs
  6. 46
      DesignPattern/State-VendingMachineExample/HasMoneyState.cs
  7. 36
      DesignPattern/State-VendingMachineExample/Product.cs
  8. 18
      DesignPattern/State-VendingMachineExample/Program.cs
  9. 36
      DesignPattern/State-VendingMachineExample/Properties/AssemblyInfo.cs
  10. 33
      DesignPattern/State-VendingMachineExample/ReadyState.cs
  11. 61
      DesignPattern/State-VendingMachineExample/State-VendingMachineExample.csproj
  12. 17
      DesignPattern/State-VendingMachineExample/VMState.cs
  13. 47
      DesignPattern/State-VendingMachineExample/VendingMachine.cs

@ -41,6 +41,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Template", "Template\Templa
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "State", "State\State.csproj", "{008D8C56-8546-4EB1-83C6-68FAF2051895}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "State-VendingMachineExample", "State-VendingMachineExample\State-VendingMachineExample.csproj", "{ED14B6E2-04BB-4F77-80E7-C5F0E945B750}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -123,6 +125,10 @@ Global
{008D8C56-8546-4EB1-83C6-68FAF2051895}.Debug|Any CPU.Build.0 = Debug|Any CPU
{008D8C56-8546-4EB1-83C6-68FAF2051895}.Release|Any CPU.ActiveCfg = Release|Any CPU
{008D8C56-8546-4EB1-83C6-68FAF2051895}.Release|Any CPU.Build.0 = Release|Any CPU
{ED14B6E2-04BB-4F77-80E7-C5F0E945B750}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ED14B6E2-04BB-4F77-80E7-C5F0E945B750}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ED14B6E2-04BB-4F77-80E7-C5F0E945B750}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ED14B6E2-04BB-4F77-80E7-C5F0E945B750}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8.1" />
</startup>
</configuration>

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace State_VendingMachineExample
{
internal class Client
{
public static void HowToTest()
{
VendingMachine vm = new VendingMachine();
vm.AddMoney(1);
vm.AddMoney(1);
vm.AddMoney(1);
vm.AddMoney(1);
vm.SelectItem(101);
}
}
}

@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace State_VendingMachineExample
{
internal class DispenseChangeState : VMState
{
public DispenseChangeState(VendingMachine context)
{
vendingMachine = context;
}
public override void AddMoney(decimal money)
{
throw new ApplicationException();
}
public override void ReturnChange(decimal money)
{
// Return charge here
if (vendingMachine.Money > 0)
{
Console.WriteLine($"Return charge ${money}");
vendingMachine.Money -= money;
}
vendingMachine.State = vendingMachine.ReadyState;
}
public override void SelectItem(int itemId)
{
throw new ApplicationException();
}
}
}

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace State_VendingMachineExample
{
internal class DispenseItemState : VMState
{
public DispenseItemState(VendingMachine context)
{
vendingMachine = context;
}
public override void AddMoney(decimal money)
{
throw new ApplicationException();
}
public override void ReturnChange(decimal money)
{
throw new ApplicationException();
}
public override void SelectItem(int itemId)
{
decimal? price = vendingMachine.GetPrice(itemId).Value;
// Dispense item here
Console.WriteLine($"Dispense Item#{itemId} ({price.Value})");
vendingMachine.Money -= price.Value;
vendingMachine.State = vendingMachine.DispenseChangeState;
vendingMachine.State.ReturnChange(vendingMachine.Money);
}
}
}

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace State_VendingMachineExample
{
internal class HasMoneyState : VMState
{
public HasMoneyState(VendingMachine context)
{
vendingMachine = context;
}
public override void AddMoney(decimal money)
{
vendingMachine.Money += money;
Console.WriteLine($"Add ${money}, Balance: {vendingMachine.Money}");
}
public override void ReturnChange(decimal money)
{
throw new ApplicationException();
}
public override void SelectItem(int itemId)
{
decimal? price = vendingMachine.GetPrice(itemId).Value;
if (!price.HasValue)
{
Console.WriteLine($"{itemId} not found");
return;
}
if (vendingMachine.Money < price.Value)
{
Console.WriteLine("Insufficient money");
return;
}
vendingMachine.State = vendingMachine.DispenseItemState;
vendingMachine.State.SelectItem(itemId);
}
}
}

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace State_VendingMachineExample
{
internal class Product
{
private List<Item> items;
public Product()
{
items = new List<Item>()
{
new Item() { Id = 101, Price = 3.50M },
new Item() { Id = 201, Price = 4.50M },
new Item() { Id = 301, Price = 4.50M }
};
}
public decimal? GetPrice(int itemId)
{
Item item = items.SingleOrDefault(x => x.Id == itemId);
return item == null ? null : (decimal?)item.Price;
}
private class Item
{
public int Id { get; set; }
public decimal Price { get; set; }
}
}
}

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace State_VendingMachineExample
{
internal class Program
{
static void Main(string[] args)
{
Client.HowToTest();
Console.ReadKey();
}
}
}

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해
// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면
// 이러한 특성 값을 변경하세요.
[assembly: AssemblyTitle("State-VendingMachineExample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("State-VendingMachineExample")]
[assembly: AssemblyCopyright("Copyright © 2022")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에
// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면
// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요.
[assembly: ComVisible(false)]
// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다.
[assembly: Guid("ed14b6e2-04bb-4f77-80e7-c5f0e945b750")]
// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다.
//
// 주 버전
// 부 버전
// 빌드 번호
// 수정 버전
//
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를
// 기본값으로 할 수 있습니다.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace State_VendingMachineExample
{
// Concrete State
internal class ReadyState : VMState
{
public ReadyState(VendingMachine context)
{
vendingMachine = context;
}
public override void AddMoney(decimal money)
{
vendingMachine.State = vendingMachine.HasMoneyState;
vendingMachine.State.AddMoney(money);
}
public override void ReturnChange(decimal money)
{
throw new ApplicationException();
}
public override void SelectItem(int itemId)
{
throw new ApplicationException();
}
}
}

@ -0,0 +1,61 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{ED14B6E2-04BB-4F77-80E7-C5F0E945B750}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>State_VendingMachineExample</RootNamespace>
<AssemblyName>State-VendingMachineExample</AssemblyName>
<TargetFrameworkVersion>v4.8.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</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="Client.cs" />
<Compile Include="DispenseChangeState.cs" />
<Compile Include="DispenseItemState.cs" />
<Compile Include="HasMoneyState.cs" />
<Compile Include="Product.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ReadyState.cs" />
<Compile Include="VendingMachine.cs" />
<Compile Include="VMState.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace State_VendingMachineExample
{
// State 인터페이스
internal abstract class VMState
{
protected VendingMachine vendingMachine;
public abstract void AddMoney(decimal money);
public abstract void SelectItem(int itemId);
public abstract void ReturnChange(decimal money);
}
}

@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace State_VendingMachineExample
{
// Context
internal class VendingMachine
{
private Product product = new Product();
internal decimal Money { get; set; }
internal VMState State { get; set; }
internal VMState ReadyState { get; private set; }
internal VMState HasMoneyState { get; private set; }
internal VMState DispenseItemState { get; private set; }
internal VMState DispenseChangeState { get; private set; }
public VendingMachine()
{
this.Money = 0;
this.ReadyState = new ReadyState(this);
this.HasMoneyState = new HasMoneyState(this);
this.DispenseItemState = new DispenseItemState(this);
this.DispenseChangeState = new DispenseChangeState(this);
this.State = this.ReadyState;
}
public void AddMoney(decimal money)
{
this.State.AddMoney(money);
}
public void SelectItem(int itemId)
{
this.State.SelectItem(itemId);
}
internal decimal? GetPrice(int itemId)
{
return product.GetPrice(itemId);
}
}
}
Loading…
Cancel
Save