├── .gitattributes
├── .gitignore
├── .upgrade-assistant
├── AdapterPattern
├── AdapterPattern.csproj
├── App.config
├── IChargingLine.cs
├── Program.cs
└── Properties
│ └── AssemblyInfo.cs
├── AnalysisReport.sarif
├── BridgePattern
├── App.config
├── BridgePattern.csproj
├── ClassDiagram1.cd
├── Manager.cs
├── ProductManger.cs
├── Program.cs
├── Project.cs
├── ProjectManager.cs
├── Properties
│ └── AssemblyInfo.cs
└── WebProject.cs
├── BuilderPattern
├── App.config
├── BuilderPattern.csproj
├── Director.cs
├── Program.cs
└── Properties
│ └── AssemblyInfo.cs
├── ChainofResponsibility
├── App.config
├── Bill.cs
├── BillHandler.cs
├── ChainofResponsibility.csproj
├── Program.cs
└── Properties
│ └── AssemblyInfo.cs
├── CommandPattern
├── App.config
├── CommandPattern.csproj
├── Invoker.cs
├── Program.cs
└── Properties
│ └── AssemblyInfo.cs
├── CompositePattern
├── App.config
├── CompositePattern.csproj
├── Organization.cs
├── Program.cs
└── Properties
│ └── AssemblyInfo.cs
├── DecoratorPattern
├── AbstractHouse.cs
├── App.config
├── DecoratorHouse.cs
├── DecoratorPattern.csproj
├── Program.cs
└── Properties
│ └── AssemblyInfo.cs
├── DesignPattern.sln
├── FacadePattern
├── ATM.cs
├── AccountSubsystem.cs
├── App.config
├── AtmFacade.cs
├── BankAccount.cs
├── BankSubsystem.cs
├── FacadePattern.csproj
├── IBankSubsystem.cs
├── Program.cs
└── Properties
│ └── AssemblyInfo.cs
├── FactoryPattern
├── AbstractBus.cs
├── AbstractCar.cs
├── AbstractFactory.cs
├── App.config
├── FactoryPattern.csproj
├── IFactoryMethod.cs
├── Program.cs
├── Properties
│ └── AssemblyInfo.cs
├── ReflectFactory.cs
└── SimpleFactory.cs
├── FlyweightPattern
├── App.config
├── Email.cs
├── EmailTemplateFactory.cs
├── FlyweightPattern.csproj
├── Program.cs
└── Properties
│ └── AssemblyInfo.cs
├── IteratorPattern
├── App.config
├── Iterator.cs
├── IteratorPattern.csproj
├── Program.cs
└── Properties
│ └── AssemblyInfo.cs
├── MediatorPattern
├── App.config
├── Mediator.cs
├── MediatorPattern.csproj
├── Program.cs
└── Properties
│ └── AssemblyInfo.cs
├── MementoPattern
├── App.config
├── Caretaker.cs
├── ContactMemento.cs
├── ContactPerson.cs
├── MementoPattern.csproj
├── Mobile.cs
├── Program.cs
└── Properties
│ └── AssemblyInfo.cs
├── ObserverPattern
├── App.config
├── DelegateImplement
│ └── FishingRod.cs
├── FishType.cs
├── ObserverPattern.csproj
├── Program.cs
├── Properties
│ └── AssemblyInfo.cs
└── SimpleImplement
│ └── FishingTool.cs
├── PrototypePattern
├── App.config
├── Email.cs
├── Program.cs
├── Properties
│ └── AssemblyInfo.cs
└── PrototypePattern.csproj
├── ProxyPattern
├── App.config
├── ISearchEngine.cs
├── Program.cs
├── Properties
│ └── AssemblyInfo.cs
└── ProxyPattern.csproj
├── README.md
├── SingletonPattern
├── App.config
├── GenericSingleton.cs
├── Program.cs
├── Properties
│ └── AssemblyInfo.cs
├── Singleton1.cs
├── Singleton2.cs
├── Singleton3.cs
├── Singleton4.cs
└── SingletonPattern.csproj
├── StatePattern
├── App.config
├── Car.cs
├── ICarState.cs
├── Program.cs
├── Properties
│ └── AssemblyInfo.cs
├── RuningState.cs
├── SpeedDownState.cs
├── SpeedUpState.cs
├── StatePattern.csproj
└── StopState.cs
├── StrategyPattern
├── App.config
├── ITravelStrategy.cs
├── Program.cs
├── Properties
│ └── AssemblyInfo.cs
└── StrategyPattern.csproj
├── TemplateMethodPattern
├── App.config
├── AssembleComputer.cs
├── Program.cs
├── Properties
│ └── AssemblyInfo.cs
└── TemplateMethodPattern.csproj
├── UpgradeReport.sarif
├── VisitorPattern
├── App.config
├── Customer.cs
├── Distributor.cs
├── Order.cs
├── OrderCenter.cs
├── OrderLine.cs
├── Picker.cs
├── Product.cs
├── Program.cs
├── Properties
│ └── AssemblyInfo.cs
├── ReturnOrder.cs
├── SaleOrder.cs
├── Visitor.cs
└── VisitorPattern.csproj
└── upgrade-assistant.clef
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | [Xx]64/
19 | [Xx]86/
20 | [Bb]uild/
21 | bld/
22 | [Bb]in/
23 | [Oo]bj/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | artifacts/
46 |
47 | *_i.c
48 | *_p.c
49 | *_i.h
50 | *.ilk
51 | *.meta
52 | *.obj
53 | *.pch
54 | *.pdb
55 | *.pgc
56 | *.pgd
57 | *.rsp
58 | *.sbr
59 | *.tlb
60 | *.tli
61 | *.tlh
62 | *.tmp
63 | *.tmp_proj
64 | *.log
65 | *.vspscc
66 | *.vssscc
67 | .builds
68 | *.pidb
69 | *.svclog
70 | *.scc
71 |
72 | # Chutzpah Test files
73 | _Chutzpah*
74 |
75 | # Visual C++ cache files
76 | ipch/
77 | *.aps
78 | *.ncb
79 | *.opendb
80 | *.opensdf
81 | *.sdf
82 | *.cachefile
83 | *.VC.db
84 |
85 | # Visual Studio profiler
86 | *.psess
87 | *.vsp
88 | *.vspx
89 | *.sap
90 |
91 | # TFS 2012 Local Workspace
92 | $tf/
93 |
94 | # Guidance Automation Toolkit
95 | *.gpState
96 |
97 | # ReSharper is a .NET coding add-in
98 | _ReSharper*/
99 | *.[Rr]e[Ss]harper
100 | *.DotSettings.user
101 |
102 | # JustCode is a .NET coding add-in
103 | .JustCode
104 |
105 | # TeamCity is a build add-in
106 | _TeamCity*
107 |
108 | # DotCover is a Code Coverage Tool
109 | *.dotCover
110 |
111 | # NCrunch
112 | _NCrunch_*
113 | .*crunch*.local.xml
114 | nCrunchTemp_*
115 |
116 | # MightyMoose
117 | *.mm.*
118 | AutoTest.Net/
119 |
120 | # Web workbench (sass)
121 | .sass-cache/
122 |
123 | # Installshield output folder
124 | [Ee]xpress/
125 |
126 | # DocProject is a documentation generator add-in
127 | DocProject/buildhelp/
128 | DocProject/Help/*.HxT
129 | DocProject/Help/*.HxC
130 | DocProject/Help/*.hhc
131 | DocProject/Help/*.hhk
132 | DocProject/Help/*.hhp
133 | DocProject/Help/Html2
134 | DocProject/Help/html
135 |
136 | # Click-Once directory
137 | publish/
138 |
139 | # Publish Web Output
140 | *.[Pp]ublish.xml
141 | *.azurePubxml
142 |
143 | # TODO: Un-comment the next line if you do not want to checkin
144 | # your web deploy settings because they may include unencrypted
145 | # passwords
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # NuGet Packages
150 | *.nupkg
151 | # The packages folder can be ignored because of Package Restore
152 | **/packages/*
153 | # except build/, which is used as an MSBuild target.
154 | !**/packages/build/
155 | # Uncomment if necessary however generally it will be regenerated when needed
156 | #!**/packages/repositories.config
157 | # NuGet v3's project.json files produces more ignoreable files
158 | *.nuget.props
159 | *.nuget.targets
160 |
161 | # Microsoft Azure Build Output
162 | csx/
163 | *.build.csdef
164 |
165 | # Microsoft Azure Emulator
166 | ecf/
167 | rcf/
168 |
169 | # Microsoft Azure ApplicationInsights config file
170 | ApplicationInsights.config
171 |
172 | # Windows Store app package directory
173 | AppPackages/
174 | BundleArtifacts/
175 |
176 | # Visual Studio cache files
177 | # files ending in .cache can be ignored
178 | *.[Cc]ache
179 | # but keep track of directories ending in .cache
180 | !*.[Cc]ache/
181 |
182 | # Others
183 | ClientBin/
184 | [Ss]tyle[Cc]op.*
185 | ~$*
186 | *~
187 | *.dbmdl
188 | *.dbproj.schemaview
189 | *.pfx
190 | *.publishsettings
191 | node_modules/
192 | orleans.codegen.cs
193 |
194 | # RIA/Silverlight projects
195 | Generated_Code/
196 |
197 | # Backup & report files from converting an old project file
198 | # to a newer Visual Studio version. Backup files are not needed,
199 | # because we have git ;-)
200 | _UpgradeReport_Files/
201 | Backup*/
202 | UpgradeLog*.XML
203 | UpgradeLog*.htm
204 |
205 | # SQL Server files
206 | *.mdf
207 | *.ldf
208 |
209 | # Business Intelligence projects
210 | *.rdl.data
211 | *.bim.layout
212 | *.bim_*.settings
213 |
214 | # Microsoft Fakes
215 | FakesAssemblies/
216 |
217 | # GhostDoc plugin setting file
218 | *.GhostDoc.xml
219 |
220 | # Node.js Tools for Visual Studio
221 | .ntvs_analysis.dat
222 |
223 | # Visual Studio 6 build log
224 | *.plg
225 |
226 | # Visual Studio 6 workspace options file
227 | *.opt
228 |
229 | # Visual Studio LightSwitch build output
230 | **/*.HTMLClient/GeneratedArtifacts
231 | **/*.DesktopClient/GeneratedArtifacts
232 | **/*.DesktopClient/ModelManifest.xml
233 | **/*.Server/GeneratedArtifacts
234 | **/*.Server/ModelManifest.xml
235 | _Pvt_Extensions
236 |
237 | # LightSwitch generated files
238 | GeneratedArtifacts/
239 | ModelManifest.xml
240 |
241 | # Paket dependency manager
242 | .paket/paket.exe
243 |
244 | # FAKE - F# Make
245 | .fake/
--------------------------------------------------------------------------------
/.upgrade-assistant:
--------------------------------------------------------------------------------
1 | {"Build":"0.4.410601\u002B6304b1d0784e32e20ef0299db22bc9e3f6a9b3f3","CurrentProject":"AdapterPattern.csproj","EntryPoints":["AdapterPattern.csproj"],"Properties":{"BaseBackupLocation":"D:\\GitHub\\Design-Pattern.backup"}}
--------------------------------------------------------------------------------
/AdapterPattern/AdapterPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/AdapterPattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/AdapterPattern/IChargingLine.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace AdapterPattern
8 | {
9 | ///
10 | /// 充电线
11 | /// 最终要适配成的目标角色
12 | ///
13 | public interface IChargingLine
14 | {
15 | ///
16 | /// 充电方法
17 | ///
18 | void Charging();
19 | }
20 |
21 | ///
22 | /// USB数据线(支持USB-Micro端口的设备)
23 | ///
24 | public class USBMicroLine : IChargingLine
25 | {
26 | public void Charging()
27 | {
28 | Console.WriteLine("为支持USB-Micro端口的设备充电!");
29 | }
30 | }
31 |
32 | ///
33 | /// 原装数据线
34 | /// 未定义充电标准的充电方法
35 | ///
36 | public class USBLine
37 | {
38 | public void Charge()
39 | {
40 | Console.WriteLine("为设备充电!");
41 | }
42 | }
43 |
44 | ///
45 | /// 苹果充电线适配器
46 | /// 类适配器模式
47 | ///
48 | public class USBlightingLineAdapter : USBLine, IChargingLine
49 | {
50 | public void Charging()
51 | {
52 | Console.WriteLine("对USB-Lighting端口的数据线进行适配!");
53 | base.Charge();
54 | }
55 | }
56 |
57 | ///
58 | /// 小米5充电线适配器
59 | /// 对象适配器模式
60 | ///
61 | public class USBTypecLineAdapter: IChargingLine
62 | {
63 | private readonly USBLine _usbLine;
64 | public USBTypecLineAdapter(USBLine usbLine)
65 | {
66 | this._usbLine = usbLine;
67 | }
68 |
69 | public void Charging()
70 | {
71 | Console.WriteLine("对USB-TypeC端口的数据线进行适配!");
72 | this._usbLine.Charge();
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/AdapterPattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace AdapterPattern
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 | //在未定义充电标准之前,各个厂家充电线的实现各不相同,但都可以为自家品牌设备充电
14 | USBLine usbLine = new USBLine();
15 | usbLine.Charge();
16 |
17 | Console.WriteLine("-------------------");
18 | //随着电器设备越来越多,各家的充电设备不能通用,造成很多不便,为了共用,厂家联合推出标准充电接口。
19 |
20 | //USB-Micro实现标准接口。
21 | IChargingLine microLine = new USBMicroLine();
22 | microLine.Charging();
23 |
24 | Console.WriteLine("-------------------");
25 |
26 | //现在手里有一个未实现充电标准的充电线,通过适配器,为小米5设备充电
27 | Console.WriteLine("对象适配器模式:");
28 | IChargingLine typeCLineAdapter = new USBTypecLineAdapter(usbLine);
29 | typeCLineAdapter.Charging();
30 |
31 | Console.WriteLine("-------------------");
32 |
33 | //现在手里有一个未实现充电标准的充电线,通过适配器,为苹果设备充电
34 | Console.WriteLine("类适配器模式:");
35 | IChargingLine lightingLineAdapter = new USBlightingLineAdapter();
36 | lightingLineAdapter.Charging();
37 |
38 | Console.ReadLine();
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/AdapterPattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("AdapterPattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("AdapterPattern")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | //将 ComVisible 设置为 false 将使此程序集中的类型
18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("a0d5f127-471c-47ac-a9e0-f2bb72d2ef8f")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/AnalysisReport.sarif:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json",
3 | "version": "2.1.0",
4 | "runs": [
5 | {
6 | "tool": {
7 | "driver": {
8 | "name": "Dependency Analysis",
9 | "semanticVersion": "0.4.410601",
10 | "informationUri": "https://docs.microsoft.com/en-us/dotnet/core/porting/upgrade-assistant-overview",
11 | "rules": [
12 | {
13 | "id": "UA106",
14 | "name": "PackageToBeAdded",
15 | "fullDescription": {
16 | "text": "Packages that need to be added in order to upgrade the project to chosen TFM"
17 | },
18 | "helpUri": "https://docs.microsoft.com/en-us/dotnet/core/porting/upgrade-assistant-overview"
19 | }
20 | ]
21 | }
22 | },
23 | "results": [
24 | {
25 | "ruleId": "UA106",
26 | "level": "note",
27 | "message": {
28 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
29 | },
30 | "locations": [
31 | {
32 | "physicalLocation": {
33 | "artifactLocation": {
34 | "uri": "file:///D:/GitHub/Design-Pattern/FactoryPattern/FactoryPattern.csproj"
35 | },
36 | "region": {}
37 | }
38 | }
39 | ]
40 | },
41 | {
42 | "ruleId": "UA106",
43 | "level": "note",
44 | "message": {
45 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
46 | },
47 | "locations": [
48 | {
49 | "physicalLocation": {
50 | "artifactLocation": {
51 | "uri": "file:///D:/GitHub/Design-Pattern/SingletonPattern/SingletonPattern.csproj"
52 | },
53 | "region": {}
54 | }
55 | }
56 | ]
57 | },
58 | {
59 | "ruleId": "UA106",
60 | "level": "note",
61 | "message": {
62 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
63 | },
64 | "locations": [
65 | {
66 | "physicalLocation": {
67 | "artifactLocation": {
68 | "uri": "file:///D:/GitHub/Design-Pattern/BuilderPattern/BuilderPattern.csproj"
69 | },
70 | "region": {}
71 | }
72 | }
73 | ]
74 | },
75 | {
76 | "ruleId": "UA106",
77 | "level": "note",
78 | "message": {
79 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
80 | },
81 | "locations": [
82 | {
83 | "physicalLocation": {
84 | "artifactLocation": {
85 | "uri": "file:///D:/GitHub/Design-Pattern/PrototypePattern/PrototypePattern.csproj"
86 | },
87 | "region": {}
88 | }
89 | }
90 | ]
91 | },
92 | {
93 | "ruleId": "UA106",
94 | "level": "note",
95 | "message": {
96 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
97 | },
98 | "locations": [
99 | {
100 | "physicalLocation": {
101 | "artifactLocation": {
102 | "uri": "file:///D:/GitHub/Design-Pattern/TemplateMethodPattern/TemplateMethodPattern.csproj"
103 | },
104 | "region": {}
105 | }
106 | }
107 | ]
108 | },
109 | {
110 | "ruleId": "UA106",
111 | "level": "note",
112 | "message": {
113 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
114 | },
115 | "locations": [
116 | {
117 | "physicalLocation": {
118 | "artifactLocation": {
119 | "uri": "file:///D:/GitHub/Design-Pattern/ProxyPattern/ProxyPattern.csproj"
120 | },
121 | "region": {}
122 | }
123 | }
124 | ]
125 | },
126 | {
127 | "ruleId": "UA106",
128 | "level": "note",
129 | "message": {
130 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
131 | },
132 | "locations": [
133 | {
134 | "physicalLocation": {
135 | "artifactLocation": {
136 | "uri": "file:///D:/GitHub/Design-Pattern/MediatorPattern/MediatorPattern.csproj"
137 | },
138 | "region": {}
139 | }
140 | }
141 | ]
142 | },
143 | {
144 | "ruleId": "UA106",
145 | "level": "note",
146 | "message": {
147 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
148 | },
149 | "locations": [
150 | {
151 | "physicalLocation": {
152 | "artifactLocation": {
153 | "uri": "file:///D:/GitHub/Design-Pattern/CommandPattern/CommandPattern.csproj"
154 | },
155 | "region": {}
156 | }
157 | }
158 | ]
159 | },
160 | {
161 | "ruleId": "UA106",
162 | "level": "note",
163 | "message": {
164 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
165 | },
166 | "locations": [
167 | {
168 | "physicalLocation": {
169 | "artifactLocation": {
170 | "uri": "file:///D:/GitHub/Design-Pattern/ChainofResponsibility/ChainOfResponsibility.csproj"
171 | },
172 | "region": {}
173 | }
174 | }
175 | ]
176 | },
177 | {
178 | "ruleId": "UA106",
179 | "level": "note",
180 | "message": {
181 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
182 | },
183 | "locations": [
184 | {
185 | "physicalLocation": {
186 | "artifactLocation": {
187 | "uri": "file:///D:/GitHub/Design-Pattern/DecoratorPattern/DecoratorPattern.csproj"
188 | },
189 | "region": {}
190 | }
191 | }
192 | ]
193 | },
194 | {
195 | "ruleId": "UA106",
196 | "level": "note",
197 | "message": {
198 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
199 | },
200 | "locations": [
201 | {
202 | "physicalLocation": {
203 | "artifactLocation": {
204 | "uri": "file:///D:/GitHub/Design-Pattern/StrategyPattern/StrategyPattern.csproj"
205 | },
206 | "region": {}
207 | }
208 | }
209 | ]
210 | },
211 | {
212 | "ruleId": "UA106",
213 | "level": "note",
214 | "message": {
215 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
216 | },
217 | "locations": [
218 | {
219 | "physicalLocation": {
220 | "artifactLocation": {
221 | "uri": "file:///D:/GitHub/Design-Pattern/AdapterPattern/AdapterPattern.csproj"
222 | },
223 | "region": {}
224 | }
225 | }
226 | ]
227 | },
228 | {
229 | "ruleId": "UA106",
230 | "level": "note",
231 | "message": {
232 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
233 | },
234 | "locations": [
235 | {
236 | "physicalLocation": {
237 | "artifactLocation": {
238 | "uri": "file:///D:/GitHub/Design-Pattern/CompositePattern/CompositePattern.csproj"
239 | },
240 | "region": {}
241 | }
242 | }
243 | ]
244 | },
245 | {
246 | "ruleId": "UA106",
247 | "level": "note",
248 | "message": {
249 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
250 | },
251 | "locations": [
252 | {
253 | "physicalLocation": {
254 | "artifactLocation": {
255 | "uri": "file:///D:/GitHub/Design-Pattern/ObserverPattern/ObserverPattern.csproj"
256 | },
257 | "region": {}
258 | }
259 | }
260 | ]
261 | },
262 | {
263 | "ruleId": "UA106",
264 | "level": "note",
265 | "message": {
266 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
267 | },
268 | "locations": [
269 | {
270 | "physicalLocation": {
271 | "artifactLocation": {
272 | "uri": "file:///D:/GitHub/Design-Pattern/FacadePattern/FacadePattern.csproj"
273 | },
274 | "region": {}
275 | }
276 | }
277 | ]
278 | },
279 | {
280 | "ruleId": "UA106",
281 | "level": "note",
282 | "message": {
283 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
284 | },
285 | "locations": [
286 | {
287 | "physicalLocation": {
288 | "artifactLocation": {
289 | "uri": "file:///D:/GitHub/Design-Pattern/MementoPattern/MementoPattern.csproj"
290 | },
291 | "region": {}
292 | }
293 | }
294 | ]
295 | },
296 | {
297 | "ruleId": "UA106",
298 | "level": "note",
299 | "message": {
300 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
301 | },
302 | "locations": [
303 | {
304 | "physicalLocation": {
305 | "artifactLocation": {
306 | "uri": "file:///D:/GitHub/Design-Pattern/IteratorPattern/IteratorPattern.csproj"
307 | },
308 | "region": {}
309 | }
310 | }
311 | ]
312 | },
313 | {
314 | "ruleId": "UA106",
315 | "level": "note",
316 | "message": {
317 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
318 | },
319 | "locations": [
320 | {
321 | "physicalLocation": {
322 | "artifactLocation": {
323 | "uri": "file:///D:/GitHub/Design-Pattern/VisitorPattern/VisitorPattern.csproj"
324 | },
325 | "region": {}
326 | }
327 | }
328 | ]
329 | },
330 | {
331 | "ruleId": "UA106",
332 | "level": "note",
333 | "message": {
334 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
335 | },
336 | "locations": [
337 | {
338 | "physicalLocation": {
339 | "artifactLocation": {
340 | "uri": "file:///D:/GitHub/Design-Pattern/StatePattern/StatePattern.csproj"
341 | },
342 | "region": {}
343 | }
344 | }
345 | ]
346 | },
347 | {
348 | "ruleId": "UA106",
349 | "level": "note",
350 | "message": {
351 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
352 | },
353 | "locations": [
354 | {
355 | "physicalLocation": {
356 | "artifactLocation": {
357 | "uri": "file:///D:/GitHub/Design-Pattern/FlyweightPattern/FlyweightPattern.csproj"
358 | },
359 | "region": {}
360 | }
361 | }
362 | ]
363 | },
364 | {
365 | "ruleId": "UA106",
366 | "level": "note",
367 | "message": {
368 | "text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.4.410601 needs to be added."
369 | },
370 | "locations": [
371 | {
372 | "physicalLocation": {
373 | "artifactLocation": {
374 | "uri": "file:///D:/GitHub/Design-Pattern/BridgePattern/BridgePattern.csproj"
375 | },
376 | "region": {}
377 | }
378 | }
379 | ]
380 | }
381 | ],
382 | "columnKind": "utf16CodeUnits"
383 | },
384 | {
385 | "tool": {
386 | "driver": {
387 | "name": "API Upgradability",
388 | "semanticVersion": "0.4.410601",
389 | "informationUri": "https://docs.microsoft.com/en-us/dotnet/core/porting/upgrade-assistant-overview"
390 | }
391 | },
392 | "results": [],
393 | "columnKind": "utf16CodeUnits"
394 | },
395 | {
396 | "tool": {
397 | "driver": {
398 | "name": "Component Analysis",
399 | "semanticVersion": "0.4.410601",
400 | "informationUri": "https://docs.microsoft.com/en-us/dotnet/core/porting/upgrade-assistant-overview"
401 | }
402 | },
403 | "results": [],
404 | "columnKind": "utf16CodeUnits"
405 | }
406 | ]
407 | }
--------------------------------------------------------------------------------
/BridgePattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/BridgePattern/BridgePattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/BridgePattern/ClassDiagram1.cd:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | AAAAAAAAAAQAAACAAAAAAAAAIAAAAAgAAAAAAAAAAgA=
7 | Manager.cs
8 |
9 |
10 |
11 |
12 |
13 | AAAAAAAAAAQAAACAAAAAAAAAAAAAAAAAAAAAAAAAAgA=
14 | Manager.cs
15 |
16 |
17 |
18 |
19 |
20 | AAAAAAAAAAQAAACAAAAAAAAAIAAAAACAAAAAAAAAAgE=
21 | Manager.cs
22 |
23 |
24 |
25 |
26 |
27 | AAAEQAAAAAQAAAAACAAAAAQAAAAAAACAAAAAAAEAAAE=
28 | Project.cs
29 |
30 |
31 |
32 |
33 |
34 | AAAEQAAAAAQAAAAAAAAAAAQAAAAAAACAAAAAAAEAAAE=
35 | Project.cs
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/BridgePattern/Manager.cs:
--------------------------------------------------------------------------------
1 | namespace BridgePattern
2 | {
3 | public abstract class Manager
4 | {
5 | protected Project CurrentProject { get; }
6 |
7 | protected Manager(Project currentProject)
8 | {
9 | CurrentProject = currentProject;
10 | }
11 |
12 | ///
13 | /// 制定计划
14 | ///
15 | public abstract void SchedulePlan();
16 |
17 | ///
18 | /// 任务分配
19 | ///
20 | public abstract void AssignTasks();
21 |
22 | ///
23 | /// 进度把控
24 | ///
25 | public abstract void ControlProcess();
26 |
27 |
28 | ///
29 | /// 项目管理
30 | ///
31 | public virtual void ManageProject()
32 | {
33 | SchedulePlan();
34 | AssignTasks();
35 | ControlProcess();
36 | }
37 |
38 | }
39 | }
--------------------------------------------------------------------------------
/BridgePattern/ProductManger.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sheng-jie/Design-Pattern/5386b3f4777dbdc516a60053791e2f975a816fc1/BridgePattern/ProductManger.cs
--------------------------------------------------------------------------------
/BridgePattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace BridgePattern
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 | Project webProject = new WebProject("Web项目");
14 | Manager projectManager = new ProjectManager(webProject);
15 | Manager productManager = new ProductManger(webProject);
16 |
17 | projectManager.ManageProject();
18 | productManager.ManageProject();
19 |
20 | Console.ReadLine();
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/BridgePattern/Project.cs:
--------------------------------------------------------------------------------
1 | namespace BridgePattern
2 | {
3 | public abstract class Project
4 | {
5 | public string ProjectName { get; set; }
6 |
7 | protected Project(string projectName)
8 | {
9 | ProjectName = projectName;
10 | }
11 |
12 | ///
13 | /// 需求分析
14 | ///
15 | public abstract void AnalyzeRequirement();
16 |
17 | ///
18 | /// 产品设计
19 | ///
20 | public abstract void DesignProduct();
21 |
22 | ///
23 | /// 制定计划
24 | ///
25 | public abstract void MakePlan();
26 |
27 | ///
28 | /// 任务分解
29 | ///
30 | public abstract void ScheduleTask();
31 |
32 | ///
33 | /// 进度把控
34 | ///
35 | public abstract void ControlProcess();
36 |
37 | ///
38 | /// 产品发布
39 | ///
40 | public abstract void ReleaseProduct();
41 |
42 | ///
43 | /// 后期运维
44 | ///
45 | public abstract void MaintainProduct();
46 |
47 | }
48 | }
--------------------------------------------------------------------------------
/BridgePattern/ProjectManager.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace BridgePattern
4 | {
5 | ///
6 | /// 项目经理
7 | ///
8 | public class ProjectManager : Manager
9 | {
10 | public ProjectManager(Project currentProject) : base(currentProject)
11 | {
12 | }
13 |
14 | public override void SchedulePlan()
15 | {
16 | base.CurrentProject.MakePlan();
17 | }
18 |
19 | public override void AssignTasks()
20 | {
21 | base.CurrentProject.ScheduleTask();
22 | }
23 |
24 | public override void ControlProcess()
25 | {
26 | base.CurrentProject.ControlProcess();
27 | }
28 |
29 | public override void ManageProject()
30 | {
31 | Console.WriteLine($"项目经理负责【{base.CurrentProject.ProjectName}】:");
32 | base.ManageProject();
33 | }
34 | }
35 | }
--------------------------------------------------------------------------------
/BridgePattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("BridgePattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("BridgePattern")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 会使此程序集中的类型
18 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("398c32b4-e52a-4ab7-9876-c878160aac50")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/BridgePattern/WebProject.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace BridgePattern
4 | {
5 | public class WebProject : Project
6 | {
7 | public WebProject(string projectName) : base(projectName)
8 | {
9 | }
10 |
11 | public override void AnalyzeRequirement()
12 | {
13 | Console.WriteLine($"[{base.ProjectName}]:进行需求分析");
14 |
15 | }
16 |
17 | public override void DesignProduct()
18 | {
19 | Console.WriteLine($"[{base.ProjectName}]:进行产品设计");
20 | }
21 |
22 | public override void MakePlan()
23 | {
24 | Console.WriteLine($"[{base.ProjectName}]:制定项目计划");
25 | }
26 |
27 | public override void ScheduleTask()
28 | {
29 | Console.WriteLine($"[{base.ProjectName}]:制作任务清单");
30 | }
31 |
32 | public override void ControlProcess()
33 | {
34 | Console.WriteLine($"[{base.ProjectName}]:把控项目进度");
35 | }
36 |
37 | public override void ReleaseProduct()
38 | {
39 | Console.WriteLine($"[{base.ProjectName}]:产品发布");
40 | }
41 |
42 | public override void MaintainProduct()
43 | {
44 | Console.WriteLine($"[{base.ProjectName}]:后期运维");
45 | }
46 | }
47 | }
--------------------------------------------------------------------------------
/BuilderPattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/BuilderPattern/BuilderPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/BuilderPattern/Director.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace BuilderPattern
8 | {
9 | ///
10 | /// 指挥者(采购经理)
11 | ///
12 | public class Director
13 | {
14 | public Computer Construct(Builder builder)
15 | {
16 | return builder.BuildComputer();
17 | }
18 | }
19 |
20 | ///
21 | /// 建造者(模拟装机过程),也可通过接口实现
22 | /// Director不关心具体组装的细节,所以将具体的组装细节方法标记为protected
23 | ///
24 | public abstract class Builder
25 | {
26 | ///
27 | /// 组装主机
28 | ///
29 | protected abstract void BuildMainFramePart();
30 |
31 | ///
32 | /// 组装显示器
33 | ///
34 | protected abstract void BuildScreenPart();
35 |
36 | ///
37 | /// 组装输入设备(键鼠)
38 | ///
39 | protected abstract void BuildInputPart();
40 |
41 | ///
42 | /// 获取组装电脑
43 | /// 由具体的组装类决定组装顺序
44 | ///
45 | ///
46 | public abstract Computer BuildComputer();
47 | }
48 |
49 | ///
50 | /// 惠普电脑组装商
51 | ///
52 | public class HpBulider : Builder
53 | {
54 | Computer hp = new Computer() { Band = "惠普" };
55 |
56 | protected override void BuildMainFramePart()
57 | {
58 | hp.AssemblePart("主机");
59 | }
60 |
61 | protected override void BuildScreenPart()
62 | {
63 | hp.AssemblePart("显示器");
64 | }
65 |
66 | protected override void BuildInputPart()
67 | {
68 | hp.AssemblePart("键鼠");
69 | }
70 |
71 | ///
72 | /// 决定具体的组装步骤
73 | ///
74 | ///
75 | public override Computer BuildComputer()
76 | {
77 | BuildMainFramePart();
78 | BuildScreenPart();
79 | BuildInputPart();
80 | return hp;
81 | }
82 | }
83 |
84 | ///
85 | /// 戴尔电脑组装商
86 | ///
87 | public class DellBulider : Builder
88 | {
89 | Computer dell = new Computer() { Band = "戴尔" };
90 |
91 | protected override void BuildMainFramePart()
92 | {
93 | dell.AssemblePart("主机");
94 | }
95 |
96 | protected override void BuildScreenPart()
97 | {
98 | dell.AssemblePart("显示器");
99 | }
100 |
101 | protected override void BuildInputPart()
102 | {
103 | dell.AssemblePart("键鼠");
104 | }
105 |
106 | public override Computer BuildComputer()
107 | {
108 | BuildInputPart();
109 | BuildMainFramePart();
110 | BuildScreenPart();
111 | return dell;
112 | }
113 | }
114 |
115 | ///
116 | /// 产品类
117 | ///
118 | public class Computer
119 | {
120 | ///
121 | /// 品牌
122 | ///
123 | public string Band { get; set; }
124 |
125 | ///
126 | /// 电脑组件列表
127 | ///
128 | private List assemblyParts = new List();
129 |
130 | ///
131 | /// 组装部件
132 | ///
133 | /// 部件名称
134 | public void AssemblePart(string partName)
135 | {
136 | this.assemblyParts.Add(partName);
137 | }
138 |
139 | public void ShowSteps()
140 | {
141 | Console.WriteLine("开始组装『{0}』电脑:", Band);
142 | foreach (var part in assemblyParts)
143 | {
144 | Console.WriteLine(string.Format("组装『{0}』;", part));
145 | }
146 |
147 | Console.WriteLine("组装『{0}』电脑完毕!", Band);
148 | }
149 | }
150 | }
--------------------------------------------------------------------------------
/BuilderPattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace BuilderPattern
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 | Director director = new Director();
14 | HpBulider hpBuilder = new HpBulider();
15 | DellBulider dellBuilder =new DellBulider();
16 |
17 | //组装一批惠普电脑
18 | Computer hp =director.Construct(hpBuilder);
19 | hp.ShowSteps();
20 |
21 | Console.ReadLine();
22 |
23 | //组装一批戴尔电脑
24 | Computer dell = director.Construct(dellBuilder);
25 | dell.ShowSteps();
26 |
27 | Console.ReadLine();
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/BuilderPattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过以下
6 | // 特性集控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("BuilderPattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("BuilderPattern")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 使此程序集中的类型
18 | // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
19 | // 则将该类型上的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("9db8066e-f3ce-4131-bf99-d1de5f8ee82e")]
24 |
25 | // 程序集的版本信息由下面四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/ChainofResponsibility/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/ChainofResponsibility/Bill.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace ChainOfResponsibility
8 | {
9 | ///
10 | /// 单据状态枚举
11 | ///
12 | public enum BillStatus
13 | {
14 | Open,
15 | Saved,
16 | Submitted,
17 | Audited
18 | }
19 |
20 | public abstract class Bill
21 | {
22 | public string BillName { get; set; }
23 |
24 | public string BilNo { get; set; }
25 |
26 | public BillStatus Status { get; set; }
27 |
28 | public string MaterialName { get; set; }
29 |
30 | public int Qty { get; set; }
31 |
32 | public decimal Price { get; set; }
33 |
34 | public decimal Amount
35 | {
36 | get
37 | {
38 | return Qty * Price;
39 | }
40 | }
41 |
42 | ///
43 | /// 做单员
44 | ///
45 | public BillHandler BillMaker { get; set; }
46 | }
47 |
48 | public class PurchaseBill : Bill
49 | {
50 | public PurchaseBill()
51 | {
52 | base.Status = BillStatus.Open;
53 | base.BillName = "采购申请单";
54 | }
55 | }
56 |
57 |
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/ChainofResponsibility/BillHandler.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace ChainOfResponsibility
8 | {
9 | ///
10 | /// 单据处理角色
11 | ///
12 | public abstract class BillHandler
13 | {
14 | ///
15 | /// 单据处理者姓名
16 | ///
17 | public string UserName { get; set; }
18 |
19 | ///
20 | /// 单据处理者具有的权限
21 | ///
22 | public List Permissions { get; set; }
23 |
24 | public bool CheckPermission(string permission)
25 | {
26 | return Permissions.Contains(permission);
27 | }
28 |
29 | //声明下一个处理者
30 | protected BillHandler Successor { get; set; }
31 |
32 |
33 | ///
34 | /// 处理单据
35 | ///
36 | ///
37 | public void HandleBill(Bill bill)
38 | {
39 | //单据处理从保存开始
40 | if (CheckPermission("SAVE") && bill.Status == BillStatus.Open)
41 | {
42 | this.DoBillOperation(bill);
43 | }
44 | else
45 | {
46 | this.Successor.DoBillOperation(bill);
47 | }
48 | }
49 |
50 | public abstract void DoBillOperation(Bill bill);
51 |
52 | }
53 |
54 | public class Purchaser : BillHandler
55 | {
56 | private List permissions = new List() { "SAVE" };
57 |
58 | public Purchaser(string username)
59 | {
60 | base.UserName = username;
61 | base.Permissions = permissions;
62 | base.Successor = new Manager("经理--任经理");//在构造函数中指定下一个处理者
63 | }
64 |
65 | public override void DoBillOperation(Bill bill)
66 | {
67 | if (CheckPermission("SAVE") && bill.Status == BillStatus.Open)
68 | {
69 | bill.Status = BillStatus.Saved;
70 | Console.WriteLine(string.Format("{0}:{1}已经保存!", this.UserName, bill.BilNo));
71 | }
72 |
73 | if (CheckPermission("SUBMIT") && bill.Status == BillStatus.Saved)
74 | {
75 | bill.Status = BillStatus.Submitted;
76 | Console.WriteLine(string.Format("{0}:{1}已经提交!", this.UserName, bill.BilNo));
77 | }
78 |
79 | if (CheckPermission("AUDIT") && bill.Status == BillStatus.Submitted)
80 | {
81 | if (bill.Amount <= 5000)
82 | {
83 | bill.Status = BillStatus.Submitted;
84 | Console.WriteLine(string.Format("{0}:{1}已经审核!", this.UserName, bill.BilNo));
85 | }
86 | else
87 | {
88 | this.Successor.DoBillOperation(bill);
89 | }
90 |
91 | }
92 | else
93 | {
94 | this.Successor.DoBillOperation(bill);
95 | }
96 | }
97 | }
98 |
99 | public class Manager : BillHandler
100 | {
101 | private List permissions = new List() { "SAVE", "SUBMIT", "AUDIT" };
102 |
103 | public Manager(string userName)
104 | {
105 | base.UserName = userName;
106 | base.Permissions = permissions;
107 | base.Successor = new CEO("CEO--链总");
108 | }
109 |
110 | public override void DoBillOperation(Bill bill)
111 | {
112 | if (CheckPermission("SAVE") && bill.Status == BillStatus.Open)
113 | {
114 | bill.Status = BillStatus.Saved;
115 | Console.WriteLine(string.Format("{0}:{1}已经保存!", this.UserName, bill.BilNo));
116 | }
117 |
118 | if (CheckPermission("SUBMIT") && bill.Status == BillStatus.Saved)
119 | {
120 | bill.Status = BillStatus.Submitted;
121 | Console.WriteLine(string.Format("{0}:{1}已经提交!", this.UserName, bill.BilNo));
122 | }
123 |
124 | if (CheckPermission("AUDIT") && bill.Status == BillStatus.Submitted)
125 | {
126 | if (bill.Amount <= 20000)
127 | {
128 | bill.Status = BillStatus.Submitted;
129 | Console.WriteLine(string.Format("{0}:{1}已经审核!", this.UserName, bill.BilNo));
130 | }
131 | else
132 | {
133 | this.Successor.DoBillOperation(bill);
134 | }
135 |
136 | }
137 | else
138 | {
139 | this.Successor.DoBillOperation(bill);
140 | }
141 | }
142 | }
143 |
144 | public class CEO : BillHandler
145 | {
146 | private List permissions = new List() { "SAVE", "SUBMIT", "AUDIT" };
147 |
148 | public CEO(string userName)
149 | {
150 | base.UserName = userName;
151 | base.Permissions = permissions;
152 | }
153 |
154 | public override void DoBillOperation(Bill bill)
155 | {
156 | if (CheckPermission("SAVE") && bill.Status == BillStatus.Open)
157 | {
158 | bill.Status = BillStatus.Saved;
159 | Console.WriteLine(string.Format("{0}:{1}已经保存!", this.UserName, bill.BilNo));
160 | }
161 |
162 | if (CheckPermission("SUBMIT") && bill.Status == BillStatus.Saved)
163 | {
164 | bill.Status = BillStatus.Submitted;
165 | Console.WriteLine(string.Format("{0}:{1}已经提交!", this.UserName, bill.BilNo));
166 | }
167 |
168 | if (CheckPermission("AUDIT") && bill.Status == BillStatus.Submitted)
169 | {
170 | bill.Status = BillStatus.Submitted;
171 | Console.WriteLine(string.Format("{0}:{1}已经审核!", this.UserName, bill.BilNo));
172 | }
173 | }
174 | }
175 | }
176 |
--------------------------------------------------------------------------------
/ChainofResponsibility/ChainofResponsibility.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/ChainofResponsibility/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace ChainOfResponsibility
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 | PurchaseBill bill = new PurchaseBill()
14 | {
15 | BilNo = "CGDD001",
16 | MaterialName = "惠普电脑",
17 | Qty = 50,
18 | Price = 5000,
19 | BillMaker = new Purchaser("采购员--小责")
20 | //BillMaker = new Manager("经理--任经理")
21 | //BillMaker = new CEO("CEO--链总")
22 | };
23 |
24 | Console.WriteLine(string.Format("创建采购申请单:{0};申请购买{1}台{2}", bill.BilNo, bill.Qty, bill.MaterialName));
25 |
26 | bill.BillMaker.HandleBill(bill);
27 |
28 | Console.ReadLine();
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/ChainofResponsibility/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过以下
6 | // 特性集控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("ChainofResponsibility")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("ChainofResponsibility")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 使此程序集中的类型
18 | // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
19 | // 则将该类型上的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("1823f85d-2f1c-4854-b735-3331a9d425d9")]
24 |
25 | // 程序集的版本信息由下面四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/CommandPattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/CommandPattern/CommandPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/CommandPattern/Invoker.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace CommandPattern
8 | {
9 | ///
10 | /// 调用者角色
11 | ///
12 | public class Invoker
13 | {
14 | ///
15 | /// 申明调用的命令,并用构造函数注入
16 | ///
17 | private readonly Command command;
18 |
19 | public string InovkerName { get; set; }
20 |
21 | public Invoker(Command command)
22 | {
23 | this.command = command;
24 | }
25 |
26 | ///
27 | /// 调用以执行具体命令
28 | ///
29 | public void Invoke()
30 | {
31 | Console.WriteLine(string.Format("『{0}』下达命令:{1}", this.InovkerName, this.command.CommandName));
32 | this.command.Execute();
33 | }
34 | }
35 |
36 | ///
37 | /// 命令者角色
38 | ///
39 | public abstract class Command
40 | {
41 | protected readonly Receiver receiver;
42 |
43 | public string CommandName { get; set; }
44 |
45 | public Command(Receiver receiver)
46 | {
47 | this.receiver = receiver;
48 | }
49 |
50 | ///
51 | /// 抽象执行具体命令方法
52 | /// 由之类实现
53 | ///
54 | public abstract void Execute();
55 | }
56 |
57 | ///
58 | /// 武力收复台湾命令
59 | ///
60 | public class RecaptureTaiwanByFocusCommand : Command
61 | {
62 | string commandName = "武力收复台湾!";
63 |
64 | ///
65 | /// 重写默认构造函数,指定默认接收者
66 | /// 以降低高层模块对底层模块的依赖
67 | ///
68 | public RecaptureTaiwanByFocusCommand() :
69 | base(new OperationCenter())
70 | {
71 | base.CommandName = commandName;
72 | }
73 |
74 | ///
75 | /// 也可通过构造函数重新指定接收者
76 | ///
77 | ///
78 | public RecaptureTaiwanByFocusCommand(Receiver receiver)
79 | : base(receiver)
80 | {
81 | base.CommandName = commandName;
82 | }
83 |
84 | public override void Execute()
85 | {
86 | this.receiver.Plan();
87 | this.receiver.Action();
88 | }
89 | }
90 |
91 | ///
92 | /// 和平方式收复台湾命令
93 | ///
94 | public class RecaptureTaiwanByPeaceCommand : Command
95 | {
96 | string commandName = "和平收复台湾!";
97 | ///
98 | /// 重写默认构造函数,指定默认接收者
99 | /// 以降低高层模块对底层模块的依赖
100 | ///
101 | public RecaptureTaiwanByPeaceCommand() :
102 | base(new NegotiationCenter())
103 | {
104 | base.CommandName = commandName;
105 | }
106 |
107 | ///
108 | /// 也可通过构造函数重新指定接收者
109 | ///
110 | ///
111 | public RecaptureTaiwanByPeaceCommand(Receiver receiver)
112 | : base(receiver)
113 | {
114 | base.CommandName = commandName;
115 | }
116 |
117 | public override void Execute()
118 | {
119 | this.receiver.Plan();
120 | this.receiver.Action();
121 | }
122 | }
123 |
124 |
125 | ///
126 | /// 接收者角色
127 | ///
128 | public abstract class Receiver
129 | {
130 | protected string ReceiverName { get; set; }
131 |
132 | //定义每个执行者都必须处理的业务逻辑
133 | public abstract void Plan();
134 | public abstract void Action();
135 | }
136 |
137 |
138 | ///
139 | /// 作战中心
140 | ///
141 | public class OperationCenter : Receiver
142 | {
143 | public OperationCenter()
144 | {
145 | this.ReceiverName = "作战中心";
146 | }
147 | public override void Plan()
148 | {
149 | Console.WriteLine(string.Format("{0}:制定作战计划。", this.ReceiverName));
150 | }
151 |
152 | public override void Action()
153 | {
154 | Console.WriteLine(string.Format("{0}:海陆空按照即定作战计划作战,收复台湾!", this.ReceiverName));
155 | }
156 | }
157 |
158 | ///
159 | /// 谈判中心
160 | ///
161 | public class NegotiationCenter : Receiver
162 | {
163 | public NegotiationCenter()
164 | {
165 | this.ReceiverName = "谈判中心";
166 | }
167 | public override void Plan()
168 | {
169 | Console.WriteLine(string.Format("{0}:制定谈判计划。", this.ReceiverName));
170 | }
171 |
172 | public override void Action()
173 | {
174 | Console.WriteLine(string.Format("{0}:落实谈判结果,收复台湾!", this.ReceiverName));
175 | }
176 | }
177 |
178 | }
179 |
--------------------------------------------------------------------------------
/CommandPattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace CommandPattern
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 | //申明和平收复台湾命令
14 | Command focusCommand = new RecaptureTaiwanByPeaceCommand();
15 |
16 | //申明调用者
17 | Invoker invoker = new Invoker(focusCommand);
18 | invoker.InovkerName = "习大大";
19 |
20 | //下达命令
21 | invoker.Invoke();
22 |
23 | Console.WriteLine("-------------------------------");
24 |
25 | //申明武力收复台湾命令
26 | Command peaceCommand = new RecaptureTaiwanByFocusCommand();
27 |
28 | invoker = new Invoker(peaceCommand);
29 | invoker.InovkerName = "习大大";
30 |
31 | invoker.Invoke();
32 |
33 | Console.ReadLine();
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/CommandPattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过以下
6 | // 特性集控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("CommandPattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("CommandPattern")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 使此程序集中的类型
18 | // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
19 | // 则将该类型上的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("fec6bcdc-2442-462e-bed6-a11378dea44c")]
24 |
25 | // 程序集的版本信息由下面四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/CompositePattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/CompositePattern/CompositePattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/CompositePattern/Organization.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace CompositePattern
5 | {
6 | ///
7 | /// 组织架构
8 | ///
9 | public abstract class Organization
10 | {
11 | ///
12 | /// 成员姓名
13 | ///
14 | public string MemberName { get; set; }
15 |
16 | ///
17 | /// 成员职位
18 | ///
19 | public string MemberPosition { get; set; }
20 |
21 | ///
22 | /// 直接上级
23 | ///
24 | public Organization ParentNode { get; set; }
25 |
26 | public void Display()
27 | {
28 | var basicInfo = string.Format("姓名:{0},职位:{1}", MemberName, MemberPosition);
29 | var parentInfo = ParentNode == null
30 | ? ""
31 | : string.Format(",直接上级:『姓名:{0},职位:{1}』", ParentNode.MemberName, ParentNode.MemberPosition);
32 | Console.WriteLine(basicInfo + parentInfo);
33 | }
34 | }
35 |
36 | ///
37 | /// 部门
38 | ///
39 | public class Department : Organization
40 | {
41 | private readonly List _organizationInfo = new List();
42 |
43 | public Department(string departmentName, string charge)
44 | {
45 | MemberPosition = departmentName;
46 | MemberName = charge;
47 | }
48 |
49 | public void Add(Organization org)
50 | {
51 | _organizationInfo.Add(org);
52 | org.ParentNode = this;
53 | }
54 |
55 | public void Remove(Organization org)
56 | {
57 | _organizationInfo.Remove(org);
58 | }
59 |
60 | public List GetDepartmentMembers()
61 | {
62 | return _organizationInfo;
63 | }
64 | }
65 |
66 |
67 | ///
68 | /// 员工
69 | ///
70 | public class Member : Organization
71 | {
72 | }
73 | }
--------------------------------------------------------------------------------
/CompositePattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace CompositePattern
4 | {
5 | internal class Program
6 | {
7 | private static void Main(string[] args)
8 | {
9 | Console.WriteLine("组合模式:");
10 | Console.WriteLine("-------------------");
11 |
12 | var organzation = new Department("CEO", "老总");
13 | var developDepart = new Department("研发部经理", "研哥");
14 |
15 | organzation.Add(developDepart);
16 |
17 | var projectA = new Department("Erp项目组长", "E哥");
18 |
19 | developDepart.Add(projectA);
20 |
21 | var memberX = new Member {MemberPosition = "开发工程师", MemberName = "开发X"};
22 | var memberY = new Member {MemberPosition = "开发工程师", MemberName = "开发Y"};
23 | var memberZ = new Member {MemberPosition = "测试工程师", MemberName = "测试Z"};
24 |
25 | projectA.Add(memberX);
26 | projectA.Add(memberY);
27 | projectA.Add(memberZ);
28 |
29 | Console.WriteLine("组合模式:从上往下遍历");
30 | DisplayStructure(organzation);
31 | Console.WriteLine("-------------------");
32 | Console.WriteLine();
33 |
34 | Console.WriteLine("组合模式:从下往上遍历");
35 | FindParent(memberX);
36 | Console.WriteLine("-------------------");
37 | Console.ReadLine();
38 | }
39 |
40 | ///
41 | /// 正序排序
42 | ///
43 | ///
44 | private static void DisplayStructure(Organization org)
45 | {
46 | if (org.ParentNode == null)
47 | org.Display();
48 |
49 | var departMent = (Department) org;
50 |
51 | foreach (var depart in departMent.GetDepartmentMembers())
52 | {
53 | depart.Display();
54 | if (!(depart is Member))
55 | DisplayStructure((Department) depart);
56 | }
57 | }
58 |
59 | ///
60 | /// 倒序排序
61 | ///
62 | ///
63 | private static void FindParent(Organization member)
64 | {
65 | member.Display();
66 | while (member.ParentNode != null)
67 | {
68 | member.ParentNode.Display();
69 | member = member.ParentNode;
70 | }
71 | }
72 | }
73 | }
--------------------------------------------------------------------------------
/CompositePattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("CompositePattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("CompositePattern")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | //将 ComVisible 设置为 false 将使此程序集中的类型
18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("edee3e18-5c3f-4b91-9edf-393dc42f5e3f")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/DecoratorPattern/AbstractHouse.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace DecoratorPattern
8 | {
9 | ///
10 | /// 抽象房类
11 | ///
12 | public abstract class AbstractHouse
13 | {
14 | ///
15 | /// 面积
16 | ///
17 | public double Area { get; set; }
18 |
19 | ///
20 | /// 规格
21 | ///
22 | public string Specification { get; set; }
23 |
24 | ///
25 | /// 价格
26 | ///
27 | public decimal Price { get; set; }
28 |
29 | ///
30 | /// 定义抽象方法--展示
31 | ///
32 | public abstract void Show();
33 | }
34 |
35 | ///
36 | /// 未装修房 -- 毛坯房
37 | ///
38 | public class WithoutDecoratorHouse : AbstractHouse
39 | {
40 | ///
41 | /// 毛坯房就做简要展示
42 | ///
43 | public override void Show()
44 | {
45 | Console.WriteLine(string.Format("该户型为{0}㎡,户型设计为{1},目前均价为{2}元/㎡。", this.Area, this.Specification, this.Price));
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/DecoratorPattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/DecoratorPattern/DecoratorHouse.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace DecoratorPattern
8 | {
9 | ///
10 | /// 装修房
11 | ///
12 | public abstract class DecoratorHouse : AbstractHouse
13 | {
14 | private readonly AbstractHouse house;
15 |
16 | public DecoratorHouse(AbstractHouse house)
17 | {
18 | this.house = house;
19 | }
20 | public override void Show()
21 | {
22 | this.house.Show();
23 | }
24 | }
25 |
26 | ///
27 | /// 装修房--样板房
28 | ///
29 | public class ModelHouse : DecoratorHouse
30 | {
31 | public ModelHouse(AbstractHouse house) : base(house)
32 | {
33 | }
34 |
35 | ///
36 | /// 展示样板房细节
37 | ///
38 | private void ShowDetail()
39 | {
40 | Console.WriteLine(@"
41 | * 首先,您看到的是我们大概5平方的简单实用的入户花园。
42 | * 样板间的整体按欧式风格装修,精致温馨。
43 | * 进门右看是我们的餐厨一体化设计,客厅与餐厅动线相连,扩大了整个的空间视野。
44 | * 与客厅无缝连接的是超大的观景阳台,东南朝向,阳光充沛。
45 | * 动静分离的设计,将客厅与卧室进行有效的分离,保证了私密性及舒适度。
46 | * 主卧的落地窗设计,提供了足够的室内的采光度。
47 | * 主卧旁边的是干湿分离的卫生间。
48 | * 再旁边就是两个紧挨的房间,可按居家情况设计为儿童房、老人房或书房。");
49 | }
50 |
51 | public override void Show()
52 | {
53 | base.Show();
54 | ShowDetail();
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/DecoratorPattern/DecoratorPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/DecoratorPattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace DecoratorPattern
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 | Console.WriteLine("装饰模式:");
14 | Console.WriteLine("-------------------------------------------------");
15 |
16 | Console.WriteLine("先看毛坯房:");
17 | //未经装修的毛坯房
18 | var withoutDecoratorHouse = new WithoutDecoratorHouse()
19 | {
20 | Area = 80.0,
21 | Specification="三室一厅一卫",
22 | Price = 8000
23 | };
24 |
25 | withoutDecoratorHouse.Show();
26 |
27 | Console.WriteLine("-------------------------------------------------");
28 |
29 | Console.WriteLine("再看样板房:");
30 |
31 | //对毛坯房进行装修
32 | var decoratorHouse = new ModelHouse(withoutDecoratorHouse);
33 |
34 | decoratorHouse.Show();
35 | Console.WriteLine("-------------------------------------------------");
36 |
37 |
38 | Console.ReadLine();
39 |
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/DecoratorPattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("DecoratorPattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("DecoratorPattern")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | //将 ComVisible 设置为 false 将使此程序集中的类型
18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("ad530192-de5c-469f-b2c0-9314ca5ca686")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/DesignPattern.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.26228.9
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FactoryPattern", "FactoryPattern\FactoryPattern.csproj", "{B6F92CD5-5347-4F36-96CB-2ED8B9F66C25}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SingletonPattern", "SingletonPattern\SingletonPattern.csproj", "{1DC67A01-1D89-4D4B-A7E2-400B191FFB9D}"
9 | EndProject
10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BuilderPattern", "BuilderPattern\BuilderPattern.csproj", "{F24EFFF3-8FE3-49C6-90E8-252AAB8A3332}"
11 | EndProject
12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PrototypePattern", "PrototypePattern\PrototypePattern.csproj", "{F702AE63-86D1-4396-B0D6-E448903C0139}"
13 | EndProject
14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TemplateMethodPattern", "TemplateMethodPattern\TemplateMethodPattern.csproj", "{DB115CDB-2322-4155-AA43-C73AB014B132}"
15 | EndProject
16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProxyPattern", "ProxyPattern\ProxyPattern.csproj", "{DA636B4D-244C-40A4-9B34-63CB9DC45C2F}"
17 | EndProject
18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MediatorPattern", "MediatorPattern\MediatorPattern.csproj", "{EA608B4B-5203-42F6-891D-59BEB23F3B38}"
19 | EndProject
20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CommandPattern", "CommandPattern\CommandPattern.csproj", "{D49AD28A-0DF4-4D25-8CB7-4F72371E311F}"
21 | EndProject
22 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ChainOfResponsibility", "ChainofResponsibility\ChainOfResponsibility.csproj", "{E4271E2E-3478-432D-87A4-6542FD005DAD}"
23 | EndProject
24 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DecoratorPattern", "DecoratorPattern\DecoratorPattern.csproj", "{AD530192-DE5C-469F-B2C0-9314CA5CA686}"
25 | EndProject
26 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StrategyPattern", "StrategyPattern\StrategyPattern.csproj", "{3DF008E9-391E-4F49-ADFA-CAD0D1ABA592}"
27 | EndProject
28 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdapterPattern", "AdapterPattern\AdapterPattern.csproj", "{A0D5F127-471C-47AC-A9E0-F2BB72D2EF8F}"
29 | EndProject
30 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CompositePattern", "CompositePattern\CompositePattern.csproj", "{EDEE3E18-5C3F-4B91-9EDF-393DC42F5E3F}"
31 | EndProject
32 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ObserverPattern", "ObserverPattern\ObserverPattern.csproj", "{4C79FD56-5B6A-44A6-A2F1-4F5DBCAEC907}"
33 | EndProject
34 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FacadePattern", "FacadePattern\FacadePattern.csproj", "{CA00E48A-FCA2-44F1-A7C3-DF89FD3802BE}"
35 | EndProject
36 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MementoPattern", "MementoPattern\MementoPattern.csproj", "{075919B3-9370-4DCE-9B16-ED0EDEC53735}"
37 | EndProject
38 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IteratorPattern", "IteratorPattern\IteratorPattern.csproj", "{04898517-CD60-419B-9C4D-2BE8A99C40FC}"
39 | EndProject
40 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VisitorPattern", "VisitorPattern\VisitorPattern.csproj", "{02F820F2-CE4C-4E47-8CE8-4E7C0A234D42}"
41 | EndProject
42 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{4BDF7BDF-B443-4CD7-8105-0164BC5D5F0C}"
43 | ProjectSection(SolutionItems) = preProject
44 | README.md = README.md
45 | EndProjectSection
46 | EndProject
47 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StatePattern", "StatePattern\StatePattern.csproj", "{7C82D171-CCD0-48B7-B91E-34F86918C401}"
48 | EndProject
49 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FlyweightPattern", "FlyweightPattern\FlyweightPattern.csproj", "{6C5F00EA-31B9-4868-95C7-BE61BD972205}"
50 | EndProject
51 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BridgePattern", "BridgePattern\BridgePattern.csproj", "{398C32B4-E52A-4AB7-9876-C878160AAC50}"
52 | EndProject
53 | Global
54 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
55 | Debug|Any CPU = Debug|Any CPU
56 | Release|Any CPU = Release|Any CPU
57 | EndGlobalSection
58 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
59 | {B6F92CD5-5347-4F36-96CB-2ED8B9F66C25}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
60 | {B6F92CD5-5347-4F36-96CB-2ED8B9F66C25}.Debug|Any CPU.Build.0 = Debug|Any CPU
61 | {B6F92CD5-5347-4F36-96CB-2ED8B9F66C25}.Release|Any CPU.ActiveCfg = Release|Any CPU
62 | {B6F92CD5-5347-4F36-96CB-2ED8B9F66C25}.Release|Any CPU.Build.0 = Release|Any CPU
63 | {1DC67A01-1D89-4D4B-A7E2-400B191FFB9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
64 | {1DC67A01-1D89-4D4B-A7E2-400B191FFB9D}.Debug|Any CPU.Build.0 = Debug|Any CPU
65 | {1DC67A01-1D89-4D4B-A7E2-400B191FFB9D}.Release|Any CPU.ActiveCfg = Release|Any CPU
66 | {1DC67A01-1D89-4D4B-A7E2-400B191FFB9D}.Release|Any CPU.Build.0 = Release|Any CPU
67 | {F24EFFF3-8FE3-49C6-90E8-252AAB8A3332}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
68 | {F24EFFF3-8FE3-49C6-90E8-252AAB8A3332}.Debug|Any CPU.Build.0 = Debug|Any CPU
69 | {F24EFFF3-8FE3-49C6-90E8-252AAB8A3332}.Release|Any CPU.ActiveCfg = Release|Any CPU
70 | {F24EFFF3-8FE3-49C6-90E8-252AAB8A3332}.Release|Any CPU.Build.0 = Release|Any CPU
71 | {F702AE63-86D1-4396-B0D6-E448903C0139}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
72 | {F702AE63-86D1-4396-B0D6-E448903C0139}.Debug|Any CPU.Build.0 = Debug|Any CPU
73 | {F702AE63-86D1-4396-B0D6-E448903C0139}.Release|Any CPU.ActiveCfg = Release|Any CPU
74 | {F702AE63-86D1-4396-B0D6-E448903C0139}.Release|Any CPU.Build.0 = Release|Any CPU
75 | {DB115CDB-2322-4155-AA43-C73AB014B132}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
76 | {DB115CDB-2322-4155-AA43-C73AB014B132}.Debug|Any CPU.Build.0 = Debug|Any CPU
77 | {DB115CDB-2322-4155-AA43-C73AB014B132}.Release|Any CPU.ActiveCfg = Release|Any CPU
78 | {DB115CDB-2322-4155-AA43-C73AB014B132}.Release|Any CPU.Build.0 = Release|Any CPU
79 | {DA636B4D-244C-40A4-9B34-63CB9DC45C2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
80 | {DA636B4D-244C-40A4-9B34-63CB9DC45C2F}.Debug|Any CPU.Build.0 = Debug|Any CPU
81 | {DA636B4D-244C-40A4-9B34-63CB9DC45C2F}.Release|Any CPU.ActiveCfg = Release|Any CPU
82 | {DA636B4D-244C-40A4-9B34-63CB9DC45C2F}.Release|Any CPU.Build.0 = Release|Any CPU
83 | {EA608B4B-5203-42F6-891D-59BEB23F3B38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
84 | {EA608B4B-5203-42F6-891D-59BEB23F3B38}.Debug|Any CPU.Build.0 = Debug|Any CPU
85 | {EA608B4B-5203-42F6-891D-59BEB23F3B38}.Release|Any CPU.ActiveCfg = Release|Any CPU
86 | {EA608B4B-5203-42F6-891D-59BEB23F3B38}.Release|Any CPU.Build.0 = Release|Any CPU
87 | {D49AD28A-0DF4-4D25-8CB7-4F72371E311F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
88 | {D49AD28A-0DF4-4D25-8CB7-4F72371E311F}.Debug|Any CPU.Build.0 = Debug|Any CPU
89 | {D49AD28A-0DF4-4D25-8CB7-4F72371E311F}.Release|Any CPU.ActiveCfg = Release|Any CPU
90 | {D49AD28A-0DF4-4D25-8CB7-4F72371E311F}.Release|Any CPU.Build.0 = Release|Any CPU
91 | {E4271E2E-3478-432D-87A4-6542FD005DAD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
92 | {E4271E2E-3478-432D-87A4-6542FD005DAD}.Debug|Any CPU.Build.0 = Debug|Any CPU
93 | {E4271E2E-3478-432D-87A4-6542FD005DAD}.Release|Any CPU.ActiveCfg = Release|Any CPU
94 | {E4271E2E-3478-432D-87A4-6542FD005DAD}.Release|Any CPU.Build.0 = Release|Any CPU
95 | {AD530192-DE5C-469F-B2C0-9314CA5CA686}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
96 | {AD530192-DE5C-469F-B2C0-9314CA5CA686}.Debug|Any CPU.Build.0 = Debug|Any CPU
97 | {AD530192-DE5C-469F-B2C0-9314CA5CA686}.Release|Any CPU.ActiveCfg = Release|Any CPU
98 | {AD530192-DE5C-469F-B2C0-9314CA5CA686}.Release|Any CPU.Build.0 = Release|Any CPU
99 | {3DF008E9-391E-4F49-ADFA-CAD0D1ABA592}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
100 | {3DF008E9-391E-4F49-ADFA-CAD0D1ABA592}.Debug|Any CPU.Build.0 = Debug|Any CPU
101 | {3DF008E9-391E-4F49-ADFA-CAD0D1ABA592}.Release|Any CPU.ActiveCfg = Release|Any CPU
102 | {3DF008E9-391E-4F49-ADFA-CAD0D1ABA592}.Release|Any CPU.Build.0 = Release|Any CPU
103 | {A0D5F127-471C-47AC-A9E0-F2BB72D2EF8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
104 | {A0D5F127-471C-47AC-A9E0-F2BB72D2EF8F}.Debug|Any CPU.Build.0 = Debug|Any CPU
105 | {A0D5F127-471C-47AC-A9E0-F2BB72D2EF8F}.Release|Any CPU.ActiveCfg = Release|Any CPU
106 | {A0D5F127-471C-47AC-A9E0-F2BB72D2EF8F}.Release|Any CPU.Build.0 = Release|Any CPU
107 | {EDEE3E18-5C3F-4B91-9EDF-393DC42F5E3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
108 | {EDEE3E18-5C3F-4B91-9EDF-393DC42F5E3F}.Debug|Any CPU.Build.0 = Debug|Any CPU
109 | {EDEE3E18-5C3F-4B91-9EDF-393DC42F5E3F}.Release|Any CPU.ActiveCfg = Release|Any CPU
110 | {EDEE3E18-5C3F-4B91-9EDF-393DC42F5E3F}.Release|Any CPU.Build.0 = Release|Any CPU
111 | {4C79FD56-5B6A-44A6-A2F1-4F5DBCAEC907}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
112 | {4C79FD56-5B6A-44A6-A2F1-4F5DBCAEC907}.Debug|Any CPU.Build.0 = Debug|Any CPU
113 | {4C79FD56-5B6A-44A6-A2F1-4F5DBCAEC907}.Release|Any CPU.ActiveCfg = Release|Any CPU
114 | {4C79FD56-5B6A-44A6-A2F1-4F5DBCAEC907}.Release|Any CPU.Build.0 = Release|Any CPU
115 | {CA00E48A-FCA2-44F1-A7C3-DF89FD3802BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
116 | {CA00E48A-FCA2-44F1-A7C3-DF89FD3802BE}.Debug|Any CPU.Build.0 = Debug|Any CPU
117 | {CA00E48A-FCA2-44F1-A7C3-DF89FD3802BE}.Release|Any CPU.ActiveCfg = Release|Any CPU
118 | {CA00E48A-FCA2-44F1-A7C3-DF89FD3802BE}.Release|Any CPU.Build.0 = Release|Any CPU
119 | {075919B3-9370-4DCE-9B16-ED0EDEC53735}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
120 | {075919B3-9370-4DCE-9B16-ED0EDEC53735}.Debug|Any CPU.Build.0 = Debug|Any CPU
121 | {075919B3-9370-4DCE-9B16-ED0EDEC53735}.Release|Any CPU.ActiveCfg = Release|Any CPU
122 | {075919B3-9370-4DCE-9B16-ED0EDEC53735}.Release|Any CPU.Build.0 = Release|Any CPU
123 | {04898517-CD60-419B-9C4D-2BE8A99C40FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
124 | {04898517-CD60-419B-9C4D-2BE8A99C40FC}.Debug|Any CPU.Build.0 = Debug|Any CPU
125 | {04898517-CD60-419B-9C4D-2BE8A99C40FC}.Release|Any CPU.ActiveCfg = Release|Any CPU
126 | {04898517-CD60-419B-9C4D-2BE8A99C40FC}.Release|Any CPU.Build.0 = Release|Any CPU
127 | {02F820F2-CE4C-4E47-8CE8-4E7C0A234D42}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
128 | {02F820F2-CE4C-4E47-8CE8-4E7C0A234D42}.Debug|Any CPU.Build.0 = Debug|Any CPU
129 | {02F820F2-CE4C-4E47-8CE8-4E7C0A234D42}.Release|Any CPU.ActiveCfg = Release|Any CPU
130 | {02F820F2-CE4C-4E47-8CE8-4E7C0A234D42}.Release|Any CPU.Build.0 = Release|Any CPU
131 | {7C82D171-CCD0-48B7-B91E-34F86918C401}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
132 | {7C82D171-CCD0-48B7-B91E-34F86918C401}.Debug|Any CPU.Build.0 = Debug|Any CPU
133 | {7C82D171-CCD0-48B7-B91E-34F86918C401}.Release|Any CPU.ActiveCfg = Release|Any CPU
134 | {7C82D171-CCD0-48B7-B91E-34F86918C401}.Release|Any CPU.Build.0 = Release|Any CPU
135 | {6C5F00EA-31B9-4868-95C7-BE61BD972205}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
136 | {6C5F00EA-31B9-4868-95C7-BE61BD972205}.Debug|Any CPU.Build.0 = Debug|Any CPU
137 | {6C5F00EA-31B9-4868-95C7-BE61BD972205}.Release|Any CPU.ActiveCfg = Release|Any CPU
138 | {6C5F00EA-31B9-4868-95C7-BE61BD972205}.Release|Any CPU.Build.0 = Release|Any CPU
139 | {398C32B4-E52A-4AB7-9876-C878160AAC50}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
140 | {398C32B4-E52A-4AB7-9876-C878160AAC50}.Debug|Any CPU.Build.0 = Debug|Any CPU
141 | {398C32B4-E52A-4AB7-9876-C878160AAC50}.Release|Any CPU.ActiveCfg = Release|Any CPU
142 | {398C32B4-E52A-4AB7-9876-C878160AAC50}.Release|Any CPU.Build.0 = Release|Any CPU
143 | EndGlobalSection
144 | GlobalSection(SolutionProperties) = preSolution
145 | HideSolutionNode = FALSE
146 | EndGlobalSection
147 | EndGlobal
148 |
--------------------------------------------------------------------------------
/FacadePattern/ATM.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace FacadePattern
4 | {
5 | public class ATM
6 | {
7 | public void DisplayUi()
8 | {
9 | var facade = new AtmFacade();
10 |
11 | while (true)
12 | try
13 | {
14 | if (!facade.IsLogin())
15 | {
16 | Console.WriteLine("请输入银行卡号:");
17 | var bkNo = Console.ReadLine();
18 | Console.WriteLine("请输入密码:");
19 | var pwd = Console.ReadLine();
20 | facade.Login(bkNo, pwd);
21 | }
22 | else
23 | {
24 | ShowBusiness(facade);
25 | }
26 | }
27 | catch (Exception ex)
28 | {
29 | Console.ForegroundColor = ConsoleColor.Red;
30 | Console.WriteLine(ex.Message);
31 | Console.ResetColor();
32 | }
33 | }
34 |
35 |
36 | private static void ShowBusiness(AtmFacade facade)
37 | {
38 | Console.WriteLine("==========================================");
39 | Console.WriteLine("欢迎你!请选择服务项目:");
40 | Console.WriteLine("1、取款");
41 | Console.WriteLine("2、存款");
42 | Console.WriteLine("3、转账");
43 | Console.WriteLine("4、查询余额");
44 | Console.WriteLine("5、清屏");
45 | Console.WriteLine("==========================================");
46 |
47 | var pressKey = Console.ReadKey();
48 |
49 | switch (pressKey.Key)
50 | {
51 | case ConsoleKey.D1:
52 | Console.WriteLine();
53 | Console.WriteLine("请输入取款金额:");
54 | var money = Convert.ToInt32(Console.ReadLine());
55 | facade.WithdrewCash(money);
56 | break;
57 | case ConsoleKey.D2:
58 | Console.WriteLine();
59 | Console.WriteLine("请输入存款金额:");
60 | var depositNum = Convert.ToInt32(Console.ReadLine());
61 | facade.DepositCash(depositNum);
62 | break;
63 | case ConsoleKey.D3:
64 | Console.WriteLine();
65 | Console.WriteLine("请输入目标账号:");
66 | var targetNo = Console.ReadLine();
67 | Console.WriteLine("请输入转账金额:");
68 | var transferNum = Convert.ToInt32(Console.ReadLine());
69 | facade.TransferMoney(targetNo, transferNum);
70 | break;
71 | case ConsoleKey.D4:
72 | Console.WriteLine();
73 | facade.QueryBalance();
74 | break;
75 | case ConsoleKey.D5:
76 | Console.Clear();
77 | break;
78 | default:
79 | Console.ForegroundColor = ConsoleColor.Red;
80 | Console.WriteLine("输入有误,请重新输入");
81 | Console.ResetColor();
82 | break;
83 | }
84 | }
85 | }
86 | }
--------------------------------------------------------------------------------
/FacadePattern/AccountSubsystem.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 |
5 | namespace FacadePattern
6 | {
7 | ///
8 | /// 账户管理子系统
9 | ///
10 | public static class AccountSubsystem
11 | {
12 | private static readonly List Accounts = new List
13 | {
14 | new BankAccount("123455", "555555", "圣杰", "138****9309", 1000000),
15 | new BankAccount("123454", "444444", "产品汪", "157****9309", 2000000),
16 | new BankAccount("123453", "333333", "运营喵", "154****9309", 3000000),
17 | new BankAccount("123452", "222222", "程序猿", "187****9309", 4000000),
18 | new BankAccount("123451", "111111", "设计狮", "189****9309", 5000000)
19 | };
20 |
21 | public static BankAccount Login(string bankNo, string password)
22 | {
23 | var bankAccount = Accounts.FirstOrDefault(a => a.BankNo == bankNo);
24 | if (bankAccount == null)
25 | throw new Exception("无效卡号!!!");
26 |
27 | if (bankAccount.Password != password)
28 | throw new Exception("密码错误!!!");
29 |
30 | return bankAccount;
31 | }
32 |
33 | public static BankAccount GetAccount(string bankNo)
34 | {
35 | var bankAccount = Accounts.FirstOrDefault(a => a.BankNo == bankNo);
36 | if (bankAccount == null)
37 | throw new Exception("无效卡号!!!");
38 |
39 |
40 | return bankAccount;
41 | }
42 |
43 | public static void Display(BankAccount account)
44 | {
45 | Console.WriteLine("卡号:{0},持卡人姓名:{1},手机号:{2},余额:{3}", account.BankNo, account.Name, account.Phone,
46 | account.TotalMoney);
47 | }
48 |
49 |
50 | public static bool ChangePassword()
51 | {
52 | throw new NotImplementedException();
53 | }
54 | }
55 | }
--------------------------------------------------------------------------------
/FacadePattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/FacadePattern/AtmFacade.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace FacadePattern
4 | {
5 | ///
6 | /// ATM机专属门面
7 | ///
8 | public class AtmFacade
9 | {
10 | private readonly IBankSubsystem _bankSubsystem = new BankSubsystem();
11 | private BankAccount _account;
12 |
13 | public void Login(string no, string pwd)
14 | {
15 | _account = AccountSubsystem.Login(no, pwd);
16 | }
17 |
18 | public bool IsLogin()
19 | {
20 | return _account != null;
21 | }
22 |
23 | ///
24 | /// 取款
25 | ///
26 | ///
27 | public void WithdrewCash(int money)
28 | {
29 | if (_bankSubsystem.WithdrewMoney(_account, money))
30 | {
31 | Console.WriteLine("取款成功!");
32 | AccountSubsystem.Display(_account);
33 | }
34 | }
35 |
36 | ///
37 | /// 存款
38 | ///
39 | ///
40 | public void DepositCash(int money)
41 | {
42 | if (_bankSubsystem.DepositMoney(_account, money))
43 | {
44 | Console.WriteLine("存款成功!");
45 | AccountSubsystem.Display(_account);
46 | }
47 | }
48 |
49 | ///
50 | /// 查余额
51 | ///
52 | public void QueryBalance()
53 | {
54 | if (_bankSubsystem.CheckBalance(_account) > 0)
55 | AccountSubsystem.Display(_account);
56 | }
57 |
58 | ///
59 | /// 转账
60 | ///
61 | ///
62 | ///
63 | public void TransferMoney(string targetNo, int money)
64 | {
65 | if (_bankSubsystem.TransferMoney(_account, targetNo, money))
66 | {
67 | Console.WriteLine("转账成功!");
68 | AccountSubsystem.Display(_account);
69 | }
70 | }
71 | }
72 | }
--------------------------------------------------------------------------------
/FacadePattern/BankAccount.cs:
--------------------------------------------------------------------------------
1 | namespace FacadePattern
2 | {
3 | public class BankAccount
4 | {
5 | public BankAccount(string bankNo, string password, string name, string phone, int totalMoney)
6 | {
7 | BankNo = bankNo;
8 | Password = password;
9 | Name = name;
10 | Phone = phone;
11 | TotalMoney = totalMoney;
12 | }
13 |
14 | ///
15 | /// 银行卡号
16 | ///
17 | public string BankNo { get; set; }
18 |
19 | ///
20 | /// 取款密码
21 | ///
22 | public string Password { get; set; }
23 |
24 | ///
25 | /// 持卡人姓名
26 | ///
27 | public string Name { get; set; }
28 |
29 | ///
30 | /// 手机
31 | ///
32 | public string Phone { get; set; }
33 |
34 | ///
35 | /// 总金额
36 | ///
37 | public int TotalMoney { get; set; }
38 | }
39 | }
--------------------------------------------------------------------------------
/FacadePattern/BankSubsystem.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace FacadePattern
4 | {
5 | public class BankSubsystem : IBankSubsystem
6 | {
7 | ///
8 | /// 查询余额
9 | ///
10 | /// 银行账户
11 | ///
12 | public int CheckBalance(BankAccount account)
13 | {
14 | return account.TotalMoney;
15 | }
16 |
17 | ///
18 | /// 取款
19 | ///
20 | /// 银行账户
21 | /// 取多少钱
22 | /// 余额
23 | public bool WithdrewMoney(BankAccount account, int money)
24 | {
25 | if (account.TotalMoney >= money)
26 | account.TotalMoney -= money;
27 | else
28 | throw new Exception("余额不足!");
29 |
30 | return true;
31 | }
32 |
33 | ///
34 | /// 转账
35 | ///
36 | /// 转出账户
37 | /// 目标账户
38 | /// 转多少钱
39 | ///
40 | public bool TransferMoney(BankAccount account, string targetNo, int money)
41 | {
42 | var targetAccount = AccountSubsystem.GetAccount(targetNo);
43 |
44 | if (targetAccount == null)
45 | throw new Exception("目标账户不存在!");
46 |
47 | if (account.TotalMoney < money)
48 | throw new Exception("余额不足!");
49 |
50 | account.TotalMoney -= money;
51 | targetAccount.TotalMoney += money;
52 |
53 | return true;
54 | }
55 |
56 | ///
57 | /// 存款
58 | ///
59 | /// 银行账户
60 | /// 存多少钱
61 | ///
62 | public bool DepositMoney(BankAccount account, int money)
63 | {
64 | account.TotalMoney += money;
65 | return true;
66 | }
67 |
68 | ///
69 | /// 充值话费
70 | ///
71 | /// 手机号
72 | /// 银行账户
73 | /// 充值多少
74 | ///
75 | public bool RechargeMobilePhone(BankAccount account, string phoneNumber, int money)
76 | {
77 | throw new NotImplementedException();
78 | }
79 | }
80 | }
--------------------------------------------------------------------------------
/FacadePattern/FacadePattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/FacadePattern/IBankSubsystem.cs:
--------------------------------------------------------------------------------
1 | namespace FacadePattern
2 | {
3 | ///
4 | /// 银行现金业务子系统
5 | ///
6 | public interface IBankSubsystem
7 | {
8 | ///
9 | /// 查询余额
10 | ///
11 | /// 银行账户
12 | ///
13 | int CheckBalance(BankAccount account);
14 |
15 | ///
16 | /// 取款
17 | ///
18 | /// 银行账户
19 | /// 取多少钱
20 | ///
21 | bool WithdrewMoney(BankAccount account, int money);
22 |
23 | ///
24 | /// 存款
25 | ///
26 | /// 银行账户
27 | /// 存多少钱
28 | ///
29 | bool DepositMoney(BankAccount account, int money);
30 |
31 | ///
32 | /// 转账
33 | ///
34 | /// 转出账户
35 | /// 目标账户
36 | /// 转多少钱
37 | ///
38 | bool TransferMoney(BankAccount account, string targetNo, int money);
39 |
40 | ///
41 | /// 充值话费
42 | ///
43 | /// 手机号
44 | /// 银行账户
45 | /// 充值多少
46 | ///
47 | bool RechargeMobilePhone(BankAccount account, string phoneNumber, int money);
48 | }
49 | }
--------------------------------------------------------------------------------
/FacadePattern/Program.cs:
--------------------------------------------------------------------------------
1 | namespace FacadePattern
2 | {
3 | internal class Program
4 | {
5 | private static void Main(string[] args)
6 | {
7 | var atm = new ATM();
8 | atm.DisplayUi();
9 | }
10 | }
11 | }
--------------------------------------------------------------------------------
/FacadePattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("FacadePattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("FacadePattern")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | //将 ComVisible 设置为 false 将使此程序集中的类型
18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("ca00e48a-fca2-44f1-a7c3-df89fd3802be")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/FactoryPattern/AbstractBus.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace FactoryPattern
4 | {
5 | public abstract class AbstractBus
6 | {
7 | protected abstract void DoOperation();
8 |
9 | public void GetInfo()
10 | {
11 | Console.WriteLine(string.Format("I am {0}.",this.GetType().Name));
12 | }
13 | }
14 |
15 | public class ConcreateBusA : AbstractBus
16 | {
17 |
18 | protected override void DoOperation()
19 | {
20 |
21 | throw new System.NotImplementedException();
22 | }
23 | }
24 |
25 | public class ConcreateBusB : AbstractBus
26 | {
27 | protected override void DoOperation()
28 | {
29 | throw new System.NotImplementedException();
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/FactoryPattern/AbstractCar.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace FactoryPattern
8 | {
9 | public abstract class AbstractCar
10 | {
11 | protected abstract void DoOperation();
12 |
13 | public void GetInfo()
14 | {
15 | Console.WriteLine(string.Format("I am {0}.",this.GetType().Name));
16 | }
17 | }
18 |
19 | public class ConcreateCarA : AbstractCar
20 | {
21 |
22 | protected override void DoOperation()
23 | {
24 |
25 | throw new System.NotImplementedException();
26 | }
27 | }
28 |
29 | public class ConcreateCarB : AbstractCar
30 | {
31 | protected override void DoOperation()
32 | {
33 | throw new System.NotImplementedException();
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/FactoryPattern/AbstractFactory.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace FactoryPattern
8 | {
9 | ///
10 | /// 抽象工厂模式:
11 | /// 抽象工厂是应对产品族概念的,比如说,每个汽车公司可能要同时生产轿车,货车,客车,那么每一个工厂都要有创建轿车,货车和客车的方法。
12 | /// 应对产品族概念而生,增加新的产品线很容易,但是无法增加新的产品。
13 | ///
14 | public interface IAbstractFactory
15 | {
16 | AbstractCar CreateCar();
17 | AbstractBus CreateBus();
18 | }
19 |
20 | ///
21 | /// 宝马工厂
22 | ///
23 | public class BMWFactory:IAbstractFactory
24 | {
25 | public AbstractCar CreateCar()
26 | {
27 | return new ConcreateCarA();
28 | }
29 |
30 | public AbstractBus CreateBus()
31 | {
32 | return new ConcreateBusA();
33 | }
34 | }
35 |
36 | ///
37 | /// 比亚迪工厂
38 | ///
39 | public class BYDFactory : IAbstractFactory
40 | {
41 | public AbstractCar CreateCar()
42 | {
43 | return new ConcreateCarB();
44 | }
45 |
46 | public AbstractBus CreateBus()
47 | {
48 | return new ConcreateBusB();
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/FactoryPattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/FactoryPattern/FactoryPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/FactoryPattern/IFactoryMethod.cs:
--------------------------------------------------------------------------------
1 | namespace FactoryPattern
2 | {
3 | ///
4 | /// 工厂方法模式:
5 | /// 工厂方法是针对每一种产品提供一个工厂类。通过不同的工厂实例来创建不同的产品实例。
6 | /// 在同一等级结构中,支持增加任意产品。
7 | /// 符合【开放封闭原则】,但随着产品类的增加,对应的工厂也会随之增多
8 | ///
9 | public interface IFactoryMethod
10 | {
11 | AbstractCar Create();
12 | }
13 |
14 | public class ConcreateFactoryA:IFactoryMethod
15 | {
16 | public AbstractCar Create()
17 | {
18 | return new ConcreateCarA();
19 | }
20 | }
21 |
22 | public class ConcreateFactoryB : IFactoryMethod
23 | {
24 | public AbstractCar Create()
25 | {
26 | return new ConcreateCarB();
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/FactoryPattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Runtime.InteropServices;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace FactoryPattern
9 | {
10 | class Program
11 | {
12 | //简单工厂:简单实用,但违反开放封闭;
13 | //工厂方法:开放封闭,单一产品;
14 | //抽象工厂:开放封闭,多个产品;
15 | //反射工厂:可以最大限度的解耦。
16 | static void Main(string[] args)
17 | {
18 | TestSimpleFactory();
19 | TestFactoryMethod();
20 | TestReflectFactory();
21 | TestAbstractFactory();
22 | }
23 |
24 | ///
25 | /// 测试简单工厂模式
26 | ///
27 | private static void TestSimpleFactory()
28 | {
29 | Console.WriteLine("简单工厂模式:");
30 | var productA = SimpleFactory.Create(ProductEnum.ConcreateProductA);
31 | productA.GetInfo();
32 | Console.ReadLine();
33 | }
34 |
35 | ///
36 | /// 测试工厂方法模式
37 | ///
38 | private static void TestFactoryMethod()
39 | {
40 | Console.WriteLine("工厂方法模式:");
41 | IFactoryMethod factoryB =new ConcreateFactoryB();
42 | var productB = factoryB.Create();
43 | productB.GetInfo();
44 |
45 | Console.ReadLine();
46 | }
47 |
48 | ///
49 | /// 测试反射工厂模式
50 | ///
51 | private static void TestReflectFactory()
52 | {
53 | Console.WriteLine("反射工厂模式:");
54 | var productB = ReflectFactory.Create("FactoryPattern.ConcreateCarB");
55 |
56 | productB.GetInfo();
57 | Console.ReadLine();
58 | }
59 |
60 | ///
61 | /// 测试抽象工厂模式
62 | ///
63 | private static void TestAbstractFactory()
64 | {
65 | Console.WriteLine("抽象工厂模式:");
66 |
67 | var bmwFactory = new BMWFactory();
68 | bmwFactory.CreateCar().GetInfo();
69 | bmwFactory.CreateBus().GetInfo();
70 |
71 | var bydFactory = new BYDFactory();
72 | bydFactory.CreateCar().GetInfo();
73 | bydFactory.CreateBus().GetInfo();
74 |
75 | Console.ReadLine();
76 | }
77 |
78 |
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/FactoryPattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("FactoryPattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("FactoryPattern")]
13 | [assembly: AssemblyCopyright("Copyright © 2016")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("b6f92cd5-5347-4f36-96cb-2ed8b9f66c25")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/FactoryPattern/ReflectFactory.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace FactoryPattern
8 | {
9 | ///
10 | /// 反射工厂模式
11 | /// 是针对简单工厂模式的一种改进
12 | ///
13 | public static class ReflectFactory
14 | {
15 | public static AbstractCar Create(string typeName)
16 | {
17 | Type type = Type.GetType(typeName, true, true);
18 | var instance = type?.Assembly.CreateInstance(typeName) as AbstractCar;
19 |
20 | return instance;
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/FactoryPattern/SimpleFactory.cs:
--------------------------------------------------------------------------------
1 | namespace FactoryPattern
2 | {
3 | ///
4 | /// 产品枚举
5 | ///
6 | public enum ProductEnum
7 | {
8 | ConcreateProductA,
9 | ConcreateProductB
10 | }
11 |
12 | ///
13 | /// 简单工厂模式:
14 | /// 简单工厂模式的工厂类一般是使用静态方法,通过接收的参数的不同来返回不同的对象实例。
15 | /// 不修改代码的话,是无法扩展的。(如果增加新的产品,需要增加工厂的Swith分支)
16 | /// 不符合【开放封闭原则】
17 | ///
18 | public static class SimpleFactory
19 | {
20 | public static AbstractCar Create(ProductEnum productType)
21 | {
22 | switch (productType)
23 | {
24 | case ProductEnum.ConcreateProductA:
25 | return new ConcreateCarA();
26 | case ProductEnum.ConcreateProductB:
27 | return new ConcreateCarB();
28 | default:
29 | return null;
30 | }
31 | }
32 | }
33 | }
--------------------------------------------------------------------------------
/FlyweightPattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/FlyweightPattern/Email.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace FlyweightPattern
4 | {
5 | public class Email
6 | {
7 | public string Receiver { get; set; }
8 | public string Sender { get; }
9 | public string Subject { get; }
10 | public string Template { get; }
11 | public string Signature { get; }
12 |
13 | public Email(string sender, string subject, string template, string signature)
14 | {
15 | Sender = sender;
16 | Subject = subject;
17 | Template = template;
18 | Signature = signature;
19 | }
20 |
21 | }
22 | }
--------------------------------------------------------------------------------
/FlyweightPattern/EmailTemplateFactory.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Concurrent;
2 | using System.Collections.Generic;
3 |
4 | namespace FlyweightPattern
5 | {
6 | public static class EmailTemplateFactory
7 | {
8 | ///
9 | /// 预置模板
10 | ///
11 | private static readonly Dictionary SubjectAndContentMapping = new Dictionary()
12 | {
13 | {
14 | "待修复漏洞通知",
15 | @"尊敬的用户:云盾检测到您的服务器存在phpwindv9任务中心GET型CSRF代码执行漏洞,
16 | 目前已为您研发了漏洞补丁,可在云盾控制台进行一键修复。为避免该漏洞被黑客利用,
17 | 建议您尽快修复该漏洞。您可以点击此处登录云盾 - 服务器安全(安骑士)控制台进行查看和修复"
18 | },
19 | {
20 | "阿里云ECS即将到期通知",
21 | @"您有1台云服务器ECS将于一周后正式到期。未续费的云服务器ECS实例到期后将停止服务,
22 | 到期后数据为您保留7天,逾期未续费实例与磁盘会被释放,数据不可恢复。
23 | 为了保证您的服务正常运行,请及时续费。"
24 | },
25 | {"阿里云故障通告", "您的服务器存在故障,请您了解!"},
26 | {"阿里云升级通知", "我们将对阿里云进行升级,会存在服务器短暂不可用情况,请知悉!"}
27 | };
28 |
29 | ///
30 | /// 定义对象池
31 | ///
32 | static readonly ConcurrentDictionary EmailTemplates = new ConcurrentDictionary();
33 |
34 |
35 | ///
36 | /// 根据主题获取模板
37 | ///
38 | ///
39 | ///
40 | public static Email GetTemplate(string subject)
41 | {
42 | Email email = null;
43 |
44 | if (!EmailTemplates.ContainsKey(subject))
45 | {
46 | string template;
47 | SubjectAndContentMapping.TryGetValue(subject, out template);
48 | email = new Email("system@notice.aliyun.com", subject, string.IsNullOrWhiteSpace(template) ? subject : template, "阿里云计算公司");
49 | EmailTemplates.TryAdd(subject, email);
50 | }
51 | else
52 | {
53 | EmailTemplates.TryGetValue(subject, out email);
54 | }
55 |
56 | return email;
57 |
58 | }
59 |
60 | }
61 | }
--------------------------------------------------------------------------------
/FlyweightPattern/FlyweightPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/FlyweightPattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace FlyweightPattern
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 |
14 | for (int i = 0; i < 2000000; i++)
15 | {
16 | string receiver = $"kehu{i}@qq.com";
17 | //通过简单工厂维护的对象池获取已经封装好的内部状态的对象。
18 | var email = EmailTemplateFactory.GetTemplate("阿里云漏洞修复");
19 | //修改外部状态
20 | email.Receiver = receiver;
21 | SendEmail(email);
22 | }
23 |
24 | Console.ReadLine();
25 | }
26 |
27 | private static void SendEmail(Email email)
28 | {
29 | Console.WriteLine($"主题为『{email.Subject}』的邮件已发送至:{email.Receiver}");
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/FlyweightPattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("FlyweightPattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("FlyweightPattern")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 会使此程序集中的类型
18 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("6c5f00ea-31b9-4868-95c7-be61bd972205")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/IteratorPattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/IteratorPattern/Iterator.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace IteratorPattern
8 | {
9 | // 抽象聚合类
10 | public interface IListCollection
11 | {
12 | Iterator GetIterator();
13 | }
14 |
15 | // 迭代器抽象类
16 | public interface Iterator
17 | {
18 | bool MoveNext();
19 | Object GetCurrent();
20 | void Next();
21 | void Reset();
22 | }
23 |
24 | // 具体聚合类
25 | public class ConcreteList : IListCollection
26 | {
27 | readonly string[] _collection;
28 | public ConcreteList()
29 | {
30 | _collection = new string[] { "A", "B", "C", "D" };
31 | }
32 |
33 | public Iterator GetIterator()
34 | {
35 | return new ConcreteIterator(this);
36 | }
37 |
38 | public int Length
39 | {
40 | get { return _collection.Length; }
41 | }
42 |
43 | public string GetElement(int index)
44 | {
45 | return _collection[index];
46 | }
47 | }
48 |
49 | // 具体迭代器类
50 | public class ConcreteIterator : Iterator
51 | {
52 | // 迭代器要集合对象进行遍历操作,自然就需要引用集合对象
53 | private ConcreteList _list;
54 | private int _index;
55 |
56 | public ConcreteIterator(ConcreteList list)
57 | {
58 | _list = list;
59 | _index = 0;
60 | }
61 |
62 | public bool MoveNext()
63 | {
64 | if (_index < _list.Length)
65 | {
66 | return true;
67 | }
68 | return false;
69 | }
70 |
71 | public Object GetCurrent()
72 | {
73 | return _list.GetElement(_index);
74 | }
75 |
76 | public void Reset()
77 | {
78 | _index = 0;
79 | }
80 |
81 | public void Next()
82 | {
83 | if (_index < _list.Length)
84 | {
85 | _index++;
86 | }
87 |
88 | }
89 | }
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/IteratorPattern/IteratorPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/IteratorPattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace IteratorPattern
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 | Console.WriteLine("迭代器模式:");
14 | IListCollection list = new ConcreteList();
15 | var iterator = list.GetIterator();
16 |
17 | while (iterator.MoveNext())
18 | {
19 | int i = (int)iterator.GetCurrent();
20 | Console.WriteLine(i.ToString());
21 | iterator.Next();
22 | }
23 |
24 | Console.Read();
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/IteratorPattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("IteratorPattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("IteratorPattern")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | //将 ComVisible 设置为 false 将使此程序集中的类型
18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("04898517-cd60-419b-9c4d-2be8a99c40fc")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/MediatorPattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/MediatorPattern/Mediator.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace MediatorPattern
8 | {
9 | ///
10 | /// 抽象角色(模块)
11 | /// 主要实现中介的依赖注入
12 | ///
13 | public abstract class Role
14 | {
15 | protected AbstractMediator mediator;
16 |
17 | public Role(AbstractMediator mediator)
18 | {
19 | this.mediator = mediator;
20 | }
21 | }
22 |
23 | ///
24 | /// 购房(者)市场
25 | ///
26 | public class HomeBuyer : Role
27 | {
28 | private readonly string name = "购房市场:";
29 | public HomeBuyer(AbstractMediator mediator)
30 | : base(mediator)
31 | {
32 |
33 | }
34 | private static int requirement = 800;//购房需求
35 |
36 | public void BuyHouse(int num)
37 | {
38 | string rule = mediator.GetRule();
39 |
40 | Console.WriteLine(name + "需要买房:" + num + "套");
41 |
42 | if (rule != "LimitBuy")
43 | {
44 | requirement += num;
45 | }
46 | else
47 | {
48 | Console.WriteLine(name + "国家实例了限购政策,不允许购买");
49 | }
50 | }
51 |
52 | ///
53 | /// 签订购房合同
54 | ///
55 | ///
56 | public void SignAgreement(int num)
57 | {
58 | requirement -= num;
59 | Console.WriteLine(string.Format("{0}成功购房{1}套", name, num));
60 | }
61 |
62 | public int GetRequirement()
63 | {
64 | return requirement;
65 | }
66 | }
67 |
68 | ///
69 | /// 房地产商
70 | ///
71 | public class Builder : Role
72 | {
73 | private readonly string name = "房地产商:";
74 | public Builder(AbstractMediator mediator)
75 | : base(mediator)
76 | {
77 |
78 | }
79 |
80 | private static int houseNum = 1000;
81 |
82 | public void BuildHouse()
83 | {
84 | int requirement = mediator.GetBuyRequirement();
85 | if (houseNum < requirement)
86 | {
87 | //房源不够,立马新建
88 | int needBuild = requirement - houseNum + 100;
89 | Console.WriteLine(name + "建房:" + needBuild + "套");
90 | houseNum += needBuild;
91 | }
92 | }
93 |
94 | public void SaleHouse(int num)
95 | {
96 | if (houseNum < num)
97 | {
98 | string rule = mediator.GetRule();
99 |
100 | if (rule != "LimitBuild")
101 | {
102 | Console.WriteLine(name + "房源不够,正在建设中");
103 | this.BuildHouse();
104 | }
105 | }
106 | else
107 | {
108 | houseNum -= num;
109 | Console.WriteLine(name + "卖房:" + num + "套");
110 | //告诉购房者签订合同
111 | mediator.HomeBuyer.SignAgreement(num);
112 | }
113 | }
114 |
115 | public int ShowHouseNum()
116 | {
117 | return houseNum;
118 | }
119 | }
120 |
121 | ///
122 | /// 住建局
123 | ///
124 | public class ControlCenter : Role
125 | {
126 | public ControlCenter(AbstractMediator mediator)
127 | : base(mediator)
128 | {
129 |
130 | }
131 | private readonly string name = "住建局:";
132 | private static string rule;
133 |
134 | ///
135 | /// 当需大于供,限购
136 | /// 当供大于需,限建
137 | ///
138 | public void Limit()
139 | {
140 | int requirement = mediator.GetBuyRequirement();
141 | int buildingNum = mediator.GetCurrentHouseNumber();
142 |
143 | string strs = string.Format("{0}目前购房需求为:{1}套;现有房源:{2}套。", name,requirement, buildingNum);
144 |
145 | if (requirement > buildingNum)
146 | {
147 | Console.WriteLine(strs + "供小于需,开始实施限购政策");
148 | rule = "LimitBuy";
149 | }
150 | else
151 | {
152 | Console.WriteLine(strs + "供大于需,开始实施限建政策");
153 | rule = "LimitBuild";
154 | }
155 | }
156 |
157 | public string ShowRule()
158 | {
159 | return rule;
160 | }
161 |
162 | }
163 |
164 | ///
165 | /// 抽象中介,定义各模块依赖的功能
166 | ///
167 | public abstract class AbstractMediator
168 | {
169 | ///
170 | /// 使用属性注入
171 | /// 因为中介可能只需要和部分角色(模块)交互
172 | ///
173 | public HomeBuyer HomeBuyer { get; set; }
174 | public Builder HouseBuilder { get; set; }
175 | public ControlCenter ControlCenter { get; set; }
176 |
177 | ///
178 | /// 获取购房需求
179 | ///
180 | ///
181 | public abstract int GetBuyRequirement();
182 |
183 | ///
184 | /// 获取房源数目
185 | ///
186 | ///
187 | public abstract int GetCurrentHouseNumber();
188 |
189 | ///
190 | /// 获取楼市政策
191 | ///
192 | ///
193 | public abstract string GetRule();
194 |
195 | }
196 |
197 | ///
198 | /// 具体中介,实现各模块依赖的功能
199 | ///
200 | public class Mediator : AbstractMediator
201 | {
202 | public override int GetBuyRequirement()
203 | {
204 | return base.HomeBuyer.GetRequirement();
205 | }
206 |
207 | public override int GetCurrentHouseNumber()
208 | {
209 | return base.HouseBuilder.ShowHouseNum();
210 | }
211 |
212 | public override string GetRule()
213 | {
214 | return base.ControlCenter.ShowRule();
215 | }
216 | }
217 | }
218 |
--------------------------------------------------------------------------------
/MediatorPattern/MediatorPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/MediatorPattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace MediatorPattern
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 | AbstractMediator mediator = new Mediator();
14 |
15 | //声明参与的角色
16 | HomeBuyer buyer = new HomeBuyer(mediator);
17 | Builder build = new Builder(mediator);
18 | ControlCenter center = new ControlCenter(mediator);
19 |
20 | //将需要的角色注入到中介
21 | mediator.HouseBuilder = build;
22 | mediator.HomeBuyer = buyer;
23 | mediator.ControlCenter = center;
24 |
25 | int initRequirement = mediator.GetBuyRequirement();
26 | int initHousenum = mediator.GetCurrentHouseNumber();
27 |
28 | Console.WriteLine(string.Format("目前购房需求为:{0}套;现有房源:{1}套。", initRequirement, initHousenum));
29 |
30 | //买房300套
31 | buyer.BuyHouse(300);
32 |
33 | build.SaleHouse(300);
34 |
35 | //国家住建局,考察市场
36 | center.Limit();
37 |
38 | //再买房1000套
39 | buyer.BuyHouse(1000);
40 |
41 | Console.ReadLine();
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/MediatorPattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过以下
6 | // 特性集控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("MediatorPattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("MediatorPattern")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 使此程序集中的类型
18 | // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
19 | // 则将该类型上的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("34e2ba93-f856-42e5-beaf-200c2cbd51c6")]
24 |
25 | // 程序集的版本信息由下面四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/MementoPattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/MementoPattern/Caretaker.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace MementoPattern
4 | {
5 | ///
6 | /// 备忘录管理
7 | ///
8 | public class Caretaker
9 | {
10 | // 存储多个备份
11 | public Dictionary ContactMementoes { get; set; }
12 | public Caretaker()
13 | {
14 | ContactMementoes = new Dictionary();
15 | }
16 | }
17 | }
--------------------------------------------------------------------------------
/MementoPattern/ContactMemento.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace MementoPattern
8 | {
9 | ///
10 | /// 备忘录
11 | ///
12 | public class ContactMemento
13 | {
14 | private readonly List _backupContactPersons;
15 |
16 | public List GetMemento()
17 | {
18 | return _backupContactPersons;
19 | }
20 |
21 | public ContactMemento(List backupContactPersons)
22 | {
23 | _backupContactPersons = backupContactPersons;
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/MementoPattern/ContactPerson.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace MementoPattern
8 | {
9 | ///
10 | /// 联系人
11 | ///
12 | public class ContactPerson
13 | {
14 | public string Name { get; set; }
15 |
16 | public string PhoneNumber { get; set; }
17 |
18 | public ContactPerson(string name, string phoneNumber)
19 | {
20 | Name = name;
21 | PhoneNumber = phoneNumber;
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/MementoPattern/MementoPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/MementoPattern/Mobile.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace MementoPattern
8 | {
9 | ///
10 | /// 手机用户
11 | ///
12 | public class Mobile
13 | {
14 | private List _contactPersons;
15 |
16 | public List GetPhoneBook()
17 | {
18 | return _contactPersons;
19 | }
20 |
21 | public Mobile(List contactPersons)
22 | {
23 | _contactPersons = contactPersons;
24 | }
25 |
26 | ///
27 | /// 创建备份
28 | ///
29 | ///
30 | public ContactMemento CreateMemento()
31 | {
32 | //思考以下为什么要new List(_contactPersons)
33 | return new ContactMemento(new List(_contactPersons));
34 | }
35 |
36 | ///
37 | /// 恢复备份
38 | ///
39 | ///
40 | public void RestoreMemento(ContactMemento memento)
41 | {
42 | this._contactPersons = memento.GetMemento();
43 | }
44 |
45 | public void DisplayPhoneBook()
46 | {
47 | Console.WriteLine($"共有{_contactPersons.Count}位联系人,联系人列表如下:");
48 | foreach (var contactPerson in _contactPersons)
49 | {
50 | Console.WriteLine($"姓名:{contactPerson.Name},电话:{contactPerson.PhoneNumber}");
51 | }
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/MementoPattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Globalization;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading;
7 | using System.Threading.Tasks;
8 |
9 | namespace MementoPattern
10 | {
11 | class Program
12 | {
13 | static void Main(string[] args)
14 | {
15 | Console.WriteLine("======备忘录模式======");
16 |
17 | List persons = new List()
18 | {
19 | new ContactPerson("张三","13513757890"),
20 | new ContactPerson("李四","18563252369"),
21 | new ContactPerson("王二","17825635486"),
22 | };
23 |
24 | Mobile mobile = new Mobile(persons);
25 |
26 | mobile.DisplayPhoneBook();
27 |
28 | //备份通讯录
29 | Console.WriteLine("===通讯录已备份===");
30 | Caretaker caretaker = new Caretaker();
31 | string key = DateTime.Now.ToString(CultureInfo.InvariantCulture);
32 | caretaker.ContactMementoes.Add(DateTime.Now.ToString(CultureInfo.InvariantCulture), mobile.CreateMemento());
33 | Console.WriteLine($"==={key}:通讯录已备份===");
34 |
35 | //移除第一个联系人
36 | Console.WriteLine("----移除联系人----");
37 | mobile.GetPhoneBook().RemoveAt(0);
38 | mobile.DisplayPhoneBook();
39 |
40 | Thread.Sleep(2000);
41 | string key2 = DateTime.Now.ToString(CultureInfo.InvariantCulture);
42 | caretaker.ContactMementoes.Add(DateTime.Now.ToString(CultureInfo.InvariantCulture), mobile.CreateMemento());
43 | Console.WriteLine($"==={key2}:通讯录已备份===");
44 |
45 | //再移除一个联系人
46 | Console.WriteLine("----移除联系人----");
47 | mobile.GetPhoneBook().RemoveAt(0);
48 | mobile.DisplayPhoneBook();
49 |
50 | //恢复通讯录
51 | Console.WriteLine($"----恢复到最后一次通讯录备份:{caretaker.ContactMementoes.LastOrDefault().Key}----");
52 | mobile.RestoreMemento(caretaker.ContactMementoes.LastOrDefault().Value);
53 |
54 | mobile.DisplayPhoneBook();
55 |
56 | Console.ReadLine();
57 |
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/MementoPattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("MementoPattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("MementoPattern")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | //将 ComVisible 设置为 false 将使此程序集中的类型
18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("075919b3-9370-4dce-9b16-ed0edec53735")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/ObserverPattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/ObserverPattern/DelegateImplement/FishingRod.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace ObserverPattern.DelegateImplement
4 | {
5 | ///
6 | /// 鱼竿
7 | ///
8 | public class FishingRod
9 | {
10 | public delegate void FishingHandler(FishType type); //声明委托
11 | public event FishingHandler FishingEvent; //声明事件
12 |
13 | public void Fishing()
14 | {
15 | Console.WriteLine("开始下钩!");
16 |
17 | //用随机数模拟鱼咬钩,若随机数为偶数,则为鱼咬钩
18 | if (new Random().Next() % 2 == 0)
19 | {
20 | var a = new Random(10).Next();
21 | var type = (FishType) new Random().Next(0, 5);
22 | Console.WriteLine("铃铛:叮叮叮,鱼儿咬钩了");
23 | if (FishingEvent != null)
24 | FishingEvent(type);
25 | }
26 | }
27 | }
28 |
29 |
30 | ///
31 | /// 垂钓者(观察者)
32 | ///
33 | public class FishingMan
34 | {
35 | public FishingMan(string name)
36 | {
37 | Name = name;
38 | }
39 |
40 | public string Name { get; set; }
41 | public int FishCount { get; set; }
42 |
43 | public void Update(FishType type)
44 | {
45 | FishCount++;
46 | Console.WriteLine("{0}:钓到一条[{2}],已经钓到{1}条鱼了!", Name, FishCount, type);
47 | }
48 | }
49 | }
--------------------------------------------------------------------------------
/ObserverPattern/FishType.cs:
--------------------------------------------------------------------------------
1 | namespace ObserverPattern
2 | {
3 | public enum FishType
4 | {
5 | 鲫鱼,
6 | 鲤鱼,
7 | 黑鱼,
8 | 青鱼,
9 | 草鱼,
10 | 鲈鱼
11 | }
12 | }
--------------------------------------------------------------------------------
/ObserverPattern/ObserverPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/ObserverPattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Threading;
3 | using ObserverPattern.SimpleImplement;
4 |
5 | namespace ObserverPattern
6 | {
7 | internal class Program
8 | {
9 | private static void Main(string[] args)
10 | {
11 | SimpleObserverTest();
12 | Console.ReadLine();
13 | Console.WriteLine("=======================");
14 | DelegateObserverTest();
15 | Console.ReadLine();
16 | }
17 |
18 | ///
19 | /// 测试简单实现的观察者模式
20 | ///
21 | private static void SimpleObserverTest()
22 | {
23 | Console.WriteLine("简单实现的观察者模式:");
24 | Console.WriteLine("=======================");
25 | //1、初始化鱼竿
26 | var fishingRod = new FishingRod();
27 |
28 | //2、声明垂钓者
29 | var jeff = new FishingMan("圣杰");
30 |
31 | //3、将垂钓者观察鱼竿
32 | fishingRod.AddSubscriber(jeff);
33 |
34 | //4、循环钓鱼
35 | while (jeff.FishCount < 5)
36 | {
37 | fishingRod.Fishing();
38 | Console.WriteLine("-------------------");
39 | //睡眠5s
40 | Thread.Sleep(5000);
41 | }
42 | }
43 |
44 | ///
45 | /// 测试委托实现的观察者模式
46 | ///
47 | private static void DelegateObserverTest()
48 | {
49 | Console.WriteLine("委托实现的观察者模式:");
50 | Console.WriteLine("=======================");
51 | //1、初始化鱼竿
52 | var fishingRod = new DelegateImplement.FishingRod();
53 |
54 | //2、声明垂钓者
55 | var jeff = new DelegateImplement.FishingMan("圣杰");
56 |
57 | //3、注册观察者
58 | fishingRod.FishingEvent += jeff.Update;
59 |
60 | //4、循环钓鱼
61 | while (jeff.FishCount < 5)
62 | {
63 | fishingRod.Fishing();
64 | Console.WriteLine("-------------------");
65 | //睡眠5s
66 | Thread.Sleep(5000);
67 | }
68 | }
69 | }
70 | }
--------------------------------------------------------------------------------
/ObserverPattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("ObserverPattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("ObserverPattern")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | //将 ComVisible 设置为 false 将使此程序集中的类型
18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("4c79fd56-5b6a-44a6-a2f1-4f5dbcaec907")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/ObserverPattern/SimpleImplement/FishingTool.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace ObserverPattern.SimpleImplement
5 | {
6 | ///
7 | /// 钓鱼工具抽象类
8 | /// 用来维护订阅者列表,并通知订阅者
9 | ///
10 | public abstract class FishingTool
11 | {
12 | private readonly List _subscribers;
13 |
14 | protected FishingTool()
15 | {
16 | _subscribers = new List();
17 | }
18 |
19 | public void AddSubscriber(ISubscriber subscriber)
20 | {
21 | if (!_subscribers.Contains(subscriber))
22 | _subscribers.Add(subscriber);
23 | }
24 |
25 | public void RemoveSubscriber(ISubscriber subscriber)
26 | {
27 | if (_subscribers.Contains(subscriber))
28 | _subscribers.Remove(subscriber);
29 | }
30 |
31 | public void Notify(FishType type)
32 | {
33 | foreach (var subscriber in _subscribers)
34 | subscriber.Update(type);
35 | }
36 | }
37 |
38 | ///
39 | /// 鱼竿
40 | ///
41 | public class FishingRod : FishingTool
42 | {
43 | public void Fishing()
44 | {
45 | Console.WriteLine("开始下钩!");
46 |
47 | //用随机数模拟鱼咬钩,若随机数为偶数,则为鱼咬钩
48 | if (new Random().Next() % 2 == 0)
49 | {
50 | var type = (FishType) new Random().Next(0, 5);
51 | Console.WriteLine("铃铛:叮叮叮,鱼儿咬钩了");
52 | Notify(type);
53 | }
54 | }
55 | }
56 |
57 | ///
58 | /// 订阅者(观察者)接口
59 | /// 由具体的订阅者实现Update()方法
60 | ///
61 | public interface ISubscriber
62 | {
63 | void Update(FishType type);
64 | }
65 |
66 | ///
67 | /// 垂钓者实现观察者接口
68 | ///
69 | public class FishingMan : ISubscriber
70 | {
71 | public FishingMan(string name)
72 | {
73 | Name = name;
74 | }
75 |
76 | public string Name { get; set; }
77 | public int FishCount { get; set; }
78 |
79 | public void Update(FishType type)
80 | {
81 | FishCount++;
82 | Console.WriteLine("{0}:钓到一条[{2}],已经钓到{1}条鱼了!", Name, FishCount, type);
83 | }
84 | }
85 | }
--------------------------------------------------------------------------------
/PrototypePattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/PrototypePattern/Email.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace PrototypePattern
8 | {
9 | public class Email : ICloneable
10 | {
11 | public string Receiver { get; set; }
12 | public string Sender { get; set; }
13 | public string Subject { get; set; }
14 | public string Name { get; set; }
15 |
16 | public string Content { get; set; }
17 |
18 | public string Footer { get; set; }
19 |
20 |
21 | public object Clone()
22 | {
23 | return this.MemberwiseClone();
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/PrototypePattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace PrototypePattern
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 | Console.WriteLine("原型模式:");
14 |
15 | Email email = new Email()
16 | {
17 | Sender = "noreply@cmb.com",
18 | Subject = "招商银行月开鑫基金上线啦,最低年化收益7%,速速抢购!",
19 | Content = "招商银行月开鑫基金上线啦,最低年化收益7%,速速抢购,手慢无,每人限购1万,详情咨询95555!",
20 | Footer = "招商银行"
21 | };
22 |
23 | for (int i = 0; i < 10000; i++)
24 | {
25 | string receiver = string.Format("kehu{0}@qq.com", i);
26 | string name = string.Format("尊敬的客户『{0}』:", i);
27 | var cloneEmail = email.Clone() as Email;
28 | cloneEmail.Receiver = receiver;
29 | cloneEmail.Name = name;
30 |
31 | SendEmail(cloneEmail);
32 | }
33 | }
34 |
35 | private static void SendEmail(Email email)
36 | {
37 | Console.WriteLine(string.Format("邮件已发送至:『{0}』", email.Receiver));
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/PrototypePattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过以下
6 | // 特性集控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("PrototypePattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("PrototypePattern")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 使此程序集中的类型
18 | // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
19 | // 则将该类型上的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("3c2371ee-138f-4424-a7dc-daf82794fbdd")]
24 |
25 | // 程序集的版本信息由下面四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/PrototypePattern/PrototypePattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/ProxyPattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/ProxyPattern/ISearchEngine.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Net;
6 | using System.Text;
7 | using System.Threading.Tasks;
8 |
9 | namespace ProxyPattern
10 | {
11 | public interface ISearchEngine
12 | {
13 | void Search(string searchStr);
14 | }
15 |
16 | public class Google : ISearchEngine
17 | {
18 | public void Search(string searchStr)
19 | {
20 | string url = "https://www.google.com/search?q=";
21 | var request = (HttpWebRequest)WebRequest.Create(url + searchStr);
22 |
23 | var response = (HttpWebResponse)request.GetResponse();
24 |
25 | if (response != null)
26 | {
27 | Console.WriteLine(string.Format("搜索【{0}】并成功返回!", searchStr));
28 | }
29 | }
30 | }
31 |
32 | public class GoogleProxy : ISearchEngine
33 | {
34 | private readonly ISearchEngine _vpn = null;
35 |
36 | public GoogleProxy()
37 | {
38 | _vpn = new Google();
39 | }
40 |
41 | public void Search(string searchStr)
42 | {
43 | try
44 | {
45 | _vpn.Search(searchStr);
46 | }
47 | catch (Exception)
48 | {
49 | string url = "https://www.baidu.com/search?q=";
50 | var request = (HttpWebRequest)WebRequest.Create(url + searchStr);
51 |
52 | try
53 | {
54 | var response = (HttpWebResponse)request.GetResponse();
55 |
56 | if (response != null)
57 | {
58 | Console.WriteLine(string.Format("搜索【{0}】并成功返回!", searchStr));
59 | }
60 | }
61 | catch (Exception ex)
62 | {
63 | Console.WriteLine(ex.Message);
64 | }
65 | }
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/ProxyPattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace ProxyPattern
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 | Console.WriteLine("直接访问Google:");
14 | Google google = new Google();
15 | try
16 | {
17 | google.Search("特朗普");
18 | }
19 | catch (Exception ex)
20 | {
21 | Console.WriteLine(ex.Message);
22 | }
23 | Console.WriteLine("----------------------------");
24 | Console.WriteLine("使用代理访问Google:");
25 | ISearchEngine searchEngine = new GoogleProxy();
26 | searchEngine.Search("特朗普");
27 |
28 | Console.ReadLine();
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/ProxyPattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("ProxyPattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("ProxyPattern")]
13 | [assembly: AssemblyCopyright("Copyright © 2016")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("da636b4d-244c-40a4-9b34-63cb9dc45c2f")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/ProxyPattern/ProxyPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # DEMO 版本已更新至.NET 6 !!!
3 |
4 | # 『设计模式』之小试牛刀(来了就给个Star吧!)
5 |
6 |
7 | 为了更好的学习设计模式,以及督促自己完成设计模式的学习,现提笔为记。
8 | 怎么的,每周至少也要学一个设计模式!!!
9 | 恳请大家的监督和不吝赐教,共同学习和进步!
10 | 内容主要参考自《设计模式之禅》、《大话设计模式》两本书籍,以及相关网络博文!
11 |
12 |
13 |
14 | > 源码路径:[源代码](https://github.com/yanshengjie/design-pattern) ***C#***
15 |
16 |
17 | 目录
18 |
19 |
20 | 1. [想学设计模式,你得先会看类图,一张图读懂UML](http://www.jianshu.com/p/0cd7df8a7789)
21 |
22 | 2. [大致了解下都有哪些设计模式](http://www.jianshu.com/p/4a02646f7c9d)
23 |
24 | 3. [我是独一无二的『单例模式』](http://www.jianshu.com/p/2054c44dcd5a)
25 |
26 | 4. [创建相似对象,就交给『工厂模式』吧](http://www.jianshu.com/p/1275b99ca973)
27 |
28 | 5. [固定模板,不同算法,就用『模板方法模式』](http://www.jianshu.com/p/4c8d1a0a75e1)
29 |
30 | 6. [关注产出,不关心细节,『建造者模式』](http://www.jianshu.com/p/c5811ca1d208)
31 |
32 | 7. [重复构造,打出原形,『原型模式』](http://www.jianshu.com/p/ce7b981708b4)
33 |
34 | 8. [间接访问,非『代理模式』莫属](https://www.cnblogs.com/sheng-jie/p/6638690.html)
35 |
36 | 9. [系列对象,依赖交互,『中介者模式』来帮忙](http://www.jianshu.com/p/d37cd087a06f)
37 |
38 | 10. [任务分发,只管下达『命令模式』即可](http://www.jianshu.com/p/e9144a2101db)
39 |
40 | 11. [流程业务,各司其职,『责任链模式』](http://www.jianshu.com/p/95908acb842a)
41 |
42 | 12. [毛坯还是精装修,先看看样板房,『装饰模式』](http://www.jianshu.com/p/246041fc39a4)
43 |
44 | 13. [算法独立于场景而灵活变化,『策略模式』](http://www.jianshu.com/p/390fd50d02b8)
45 |
46 | 14. [新旧对接,『适配器模式』](http://www.jianshu.com/p/5e5f5024c62e)
47 |
48 | 15. [玩转集合容器,『迭代器模式』](http://www.jianshu.com/p/ae229f72c522)
49 |
50 | 16. [部分整体,树形结构,『组合模式』来帮忙](http://www.jianshu.com/p/9e49e5d702df)
51 |
52 | 17. [『观察者模式』来钓鱼](http://www.jianshu.com/p/45675c73296d)
53 |
54 | 18. [ATM取款聊聊『门面模式』](http://www.jianshu.com/p/c89a922a60c0)
55 |
56 | 19. [后悔药,『备忘录模式』](http://www.jianshu.com/p/6d46b5d3fdee)
57 |
58 | 20. [这一次数据说了算,『访问者模式』](http://www.jianshu.com/p/3aa45b6be7ae)
59 |
60 | 21. [自动驾驶谈谈『状态模式』](http://www.jianshu.com/p/42d4ca7316ad)
61 |
62 | 22. [对象复用,『享元模式』](http://www.jianshu.com/p/3fb0b559602b)
63 |
64 | 23. [牵线搭桥,『桥接模式』](http://www.jianshu.com/p/d0314ebb0617)
65 |
66 | 
67 |
--------------------------------------------------------------------------------
/SingletonPattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/SingletonPattern/GenericSingleton.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace SingletonPattern
8 | {
9 | ///
10 | /// 泛型单例模式的实现
11 | ///
12 | ///
13 | public class GenericSingleton where T : class//,new ()
14 | {
15 | private static T instance;
16 |
17 | private static readonly object Locker = new object();
18 |
19 | public static T GetInstance()
20 | {
21 | //没有第一重 instance == null 的话,每一次有线程进入 GetInstance()时,均会执行锁定操作来实现线程同步,
22 | //非常耗费性能 增加第一重instance ==null 成立时的情况下执行一次锁定以实现线程同步
23 | if (instance == null)
24 | {
25 | //Double-Check Locking 双重检查锁定
26 | lock (Locker)
27 | {
28 | if (instance == null)
29 | {
30 | //instance = new T();
31 | //需要非公共的无参构造函数,不能使用new T() ,new不支持非公共的无参构造函数
32 | instance = Activator.CreateInstance(typeof(T), true) as T;//第二个参数防止异常:“没有为该对象定义无参数的构造函数。”
33 | }
34 | }
35 | }
36 | return instance;
37 | }
38 |
39 | public void GetInfo()
40 | {
41 | Console.WriteLine(string.Format("I am {0}.", this.GetType().Name));
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/SingletonPattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading;
7 | using System.Threading.Tasks;
8 |
9 | namespace SingletonPattern
10 | {
11 | class Program
12 | {
13 | static void Main(string[] args)
14 | {
15 | Console.WriteLine("单例模式:");
16 | TestStaticSingleton();
17 | TestLasyInitialSingleton();
18 | TestGenericSingleton();
19 | TestDoubleLockSingleton();
20 | }
21 |
22 | private static void TestStaticSingleton()
23 | {
24 | Console.WriteLine("静态变量初始化实例");
25 |
26 | Singleton1 singleton1 = Singleton1.Instance();
27 | singleton1.GetInfo();
28 |
29 | Console.ReadLine();
30 | }
31 |
32 | private static void TestLasyInitialSingleton()
33 | {
34 | Console.WriteLine("延迟初始化实例");
35 |
36 | Singleton2 singleton2 = Singleton2.Instance();
37 | singleton2.GetInfo();
38 | singleton2.Reset();
39 |
40 | Console.ReadLine();
41 | }
42 |
43 | private static void TestDoubleLockSingleton()
44 | {
45 | Console.WriteLine("锁机制确保多线程只产生一个实例");
46 |
47 | for (int i = 0; i < 2; i++)
48 | {
49 | Thread thread=new Thread(ExecuteInForeground);
50 |
51 | thread.Start();
52 | }
53 | }
54 |
55 |
56 | private static void ExecuteInForeground()
57 | {
58 | Console.WriteLine("Thread {0}: {1}, Priority {2}",
59 | Thread.CurrentThread.ManagedThreadId,
60 | Thread.CurrentThread.ThreadState,
61 | Thread.CurrentThread.Priority);
62 |
63 | Singleton3 singleton3 =Singleton3.Instance();
64 | singleton3.GetInfo();
65 | Console.WriteLine(singleton3.GetHashCode());
66 | }
67 |
68 | private static void TestGenericSingleton()
69 | {
70 | Console.WriteLine("泛型单例模式:");
71 |
72 | Singleton4 instance = GenericSingleton.GetInstance();
73 |
74 | instance.GetInfo();
75 |
76 | var singleton4 = Singleton4.Instance;
77 |
78 | singleton4.GetInfo();
79 | Console.ReadLine();
80 | }
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/SingletonPattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("SingletonPattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("SingletonPattern")]
13 | [assembly: AssemblyCopyright("Copyright © 2016")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("1dc67a01-1d89-4d4b-a7e2-400b191ffb9d")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/SingletonPattern/Singleton1.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace SingletonPattern
8 | {
9 | ///
10 | /// 单例模式实现方式一:
11 | /// 静态变量初始化
12 | ///
13 | public class Singleton1
14 | {
15 | ///
16 | /// 定义为static,可以保证变量为线程安全的,即每个线程一个实例
17 | ///
18 | private static Singleton1 instance = new Singleton1();
19 |
20 | private Singleton1()
21 | {
22 |
23 | }
24 |
25 | public static Singleton1 Instance()
26 | {
27 | return instance;
28 | }
29 |
30 | public void GetInfo()
31 | {
32 | Console.WriteLine(string.Format("I am {0}.",this.GetType().Name));
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/SingletonPattern/Singleton2.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace SingletonPattern
8 | {
9 | ///
10 | /// 单例模式实现方式二:
11 | /// 延迟初始化
12 | ///
13 | public class Singleton2
14 | {
15 | ///
16 | /// 定义为static,可以保证变量为线程安全的,即每个线程一个实例
17 | ///
18 | private static Singleton2 _instance;
19 |
20 | private Singleton2()
21 | {
22 |
23 | }
24 |
25 | public static Singleton2 Instance()
26 | {
27 | return _instance ?? (_instance = new Singleton2());
28 | }
29 |
30 | ///
31 | /// 使用此方法销毁已创建的实例
32 | ///
33 | public void Reset()
34 | {
35 | _instance = null;
36 | }
37 |
38 | public void GetInfo()
39 | {
40 | Console.WriteLine(string.Format("I am {0}.",this.GetType().Name));
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/SingletonPattern/Singleton3.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace SingletonPattern
8 | {
9 | ///
10 | /// 单例模式实现方式三:
11 | /// 锁机制,确保多线程只产生一个实例
12 | ///
13 | public class Singleton3
14 | {
15 | private static Singleton3 _instance;
16 |
17 | private static readonly object Locker =new object();
18 |
19 | private Singleton3() { }
20 |
21 | public static Singleton3 Instance()
22 | {
23 | //没有第一重 instance == null 的话,每一次有线程进入 GetInstance()时,均会执行锁定操作来实现线程同步,
24 | //非常耗费性能 增加第一重instance ==null 成立时的情况下执行一次锁定以实现线程同步
25 | if (_instance==null)
26 | {
27 | lock (Locker)
28 | {
29 | //Double-Check Locking 双重检查锁定
30 | if (_instance==null)
31 | {
32 | _instance = new Singleton3();
33 | }
34 | }
35 | }
36 |
37 | return _instance;
38 | }
39 |
40 | public void GetInfo()
41 | {
42 | Console.WriteLine(string.Format("I am {0}.",this.GetType().Name));
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/SingletonPattern/Singleton4.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace SingletonPattern
8 | {
9 | ///
10 | /// 通过继承泛型单例来获取实例
11 | ///
12 | public class Singleton4
13 | {
14 | ///
15 | /// 非公共无参构造函数,确保该类无法在其他地方实例化
16 | ///
17 | private Singleton4()
18 | {
19 |
20 | }
21 |
22 | ///
23 | /// 也可以通过暴露属性获取实例
24 | ///
25 | public static Singleton4 Instance
26 | {
27 | get
28 | {
29 | return GenericSingleton.GetInstance();
30 | }
31 | }
32 |
33 | public void GetInfo()
34 | {
35 | Console.WriteLine(string.Format("I am {0}.", this.GetType().Name));
36 | }
37 |
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/SingletonPattern/SingletonPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/StatePattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/StatePattern/Car.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace StatePattern
8 | {
9 | ///
10 | /// 汽车
11 | ///
12 | public class Car
13 | {
14 | public string Name { get; set; }
15 |
16 | public Car()
17 | {
18 | this.CurrentCarState = StopState;//初始状态为停车状态
19 | }
20 |
21 | internal static ICarState StopState = new StopState();
22 | internal static ICarState RunState = new RuningState();
23 | internal static ICarState SpeedDownState = new SpeedDownState();
24 | internal static ICarState SpeedUpState = new SpeedUpState();
25 |
26 | public ICarState CurrentCarState { get; set; }
27 |
28 | public void Run()
29 | {
30 | this.CurrentCarState.Drive(this);
31 | }
32 |
33 | public void Stop()
34 | {
35 | this.CurrentCarState.Stop(this);
36 | }
37 |
38 | public void SpeedUp()
39 | {
40 | this.CurrentCarState.SpeedUp(this);
41 | }
42 | public void SpeedDown()
43 | {
44 | this.CurrentCarState.SpeedDown(this);
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/StatePattern/ICarState.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Linq;
3 | using System.Text;
4 | using System.Threading.Tasks;
5 |
6 | namespace StatePattern
7 | {
8 | ///
9 | /// 状态接口类
10 | ///
11 | public interface ICarState
12 | {
13 | ///
14 | /// 启动
15 | ///
16 | void Drive(Car car);
17 |
18 | ///
19 | /// 停车
20 | ///
21 | void Stop(Car car);
22 |
23 | ///
24 | /// 加速
25 | ///
26 | ///
27 | void SpeedUp(Car car);
28 |
29 | ///
30 | /// 减速
31 | ///
32 | ///
33 | void SpeedDown(Car car);
34 | }
35 | }
--------------------------------------------------------------------------------
/StatePattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace StatePattern
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 | Car tesla = new Car() {Name = "特斯拉 Model S"};
14 | tesla.Run();
15 | tesla.SpeedUp();
16 | tesla.SpeedDown();
17 | tesla.Stop();
18 |
19 | Console.WriteLine();
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/StatePattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("StatePattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("StatePattern")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 会使此程序集中的类型
18 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("7c82d171-ccd0-48b7-b91e-34f86918c401")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/StatePattern/RuningState.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sheng-jie/Design-Pattern/5386b3f4777dbdc516a60053791e2f975a816fc1/StatePattern/RuningState.cs
--------------------------------------------------------------------------------
/StatePattern/SpeedDownState.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace StatePattern
4 | {
5 | ///
6 | /// 减速状态
7 | ///
8 | public class SpeedDownState : ICarState
9 | {
10 | public void Drive(Car car)
11 | {
12 | Console.WriteLine("车辆正在自动驾驶!");
13 | }
14 |
15 | public void Stop(Car car)
16 | {
17 | Console.WriteLine("车辆已停止!");
18 | car.CurrentCarState = Car.StopState;
19 | }
20 |
21 | public void SpeedUp(Car car)
22 | {
23 | Console.WriteLine("路况良好,加速行驶!");
24 | car.CurrentCarState = Car.SpeedUpState;
25 | }
26 |
27 | public void SpeedDown(Car car)
28 | {
29 | Console.WriteLine("车辆正在减速行驶!");
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/StatePattern/SpeedUpState.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sheng-jie/Design-Pattern/5386b3f4777dbdc516a60053791e2f975a816fc1/StatePattern/SpeedUpState.cs
--------------------------------------------------------------------------------
/StatePattern/StatePattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/StatePattern/StopState.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sheng-jie/Design-Pattern/5386b3f4777dbdc516a60053791e2f975a816fc1/StatePattern/StopState.cs
--------------------------------------------------------------------------------
/StrategyPattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/StrategyPattern/ITravelStrategy.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace StrategyPattern
8 | {
9 | ///
10 | /// 旅行策略类
11 | ///
12 | public abstract class TravelStrategy
13 | {
14 | ///
15 | /// 目的地
16 | ///
17 | public string PlanName { get; set; }
18 |
19 | ///
20 | /// 预算
21 | ///
22 | public int Budget { get; set; }
23 | ///
24 | /// 旅游计划
25 | ///
26 | public abstract void TravelPlan();
27 | }
28 |
29 | public class GuangxiTravel : TravelStrategy
30 | {
31 | public GuangxiTravel()
32 | {
33 | this.PlanName = "广西桂林山水甲天下,心向往之!";
34 | }
35 | public override void TravelPlan()
36 | {
37 | Console.WriteLine("广西旅游计划:");
38 | Console.WriteLine(string.Format("计划名称:{0}预算:{1}", this.PlanName, this.Budget));
39 | if (this.Budget >= 4000)
40 | {
41 | Console.WriteLine("选择高铁出行!");
42 | }
43 | else
44 | {
45 | Console.WriteLine("选择大巴出行!");
46 | }
47 | }
48 | }
49 |
50 | public class BackupTravel : TravelStrategy
51 | {
52 | public BackupTravel()
53 | {
54 | this.PlanName = "逛街看电影包饺子!";
55 | }
56 | public override void TravelPlan()
57 | {
58 | Console.WriteLine("备用计划:");
59 | Console.WriteLine(string.Format("计划名称:{0}", this.PlanName));
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/StrategyPattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace StrategyPattern
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 | TravelStrategy travelPlan = null;
14 |
15 | Weather weather = (Weather)(new Random().Next(1,3));
16 | switch (weather)
17 | {
18 | case Weather.Rain:
19 | Console.WriteLine("天气糟糕");
20 | travelPlan = new BackupTravel() ;
21 | break;
22 | case Weather.Sunny:
23 | Console.WriteLine("天气晴好");
24 | travelPlan = new GuangxiTravel() { Budget = 3000 };
25 | break;
26 | }
27 |
28 | travelPlan.TravelPlan();
29 |
30 | Console.ReadLine();
31 |
32 | }
33 | }
34 |
35 | enum Weather
36 | {
37 | Sunny =1,
38 | Rain = 2
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/StrategyPattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("StrategyPattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("StrategyPattern")]
13 | [assembly: AssemblyCopyright("Copyright © 2016")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | //将 ComVisible 设置为 false 将使此程序集中的类型
18 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("3df008e9-391e-4f49-adfa-cad0d1aba592")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/StrategyPattern/StrategyPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/TemplateMethodPattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/TemplateMethodPattern/AssembleComputer.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace TemplateMethodPattern
8 | {
9 | ///
10 | /// 组装电脑
11 | ///
12 | public abstract class AssembleComputer
13 | {
14 | ///
15 | /// 组装主机
16 | ///
17 | public abstract void BuildMainFramePart();
18 |
19 | ///
20 | /// 组装显示器
21 | ///
22 | public abstract void BuildScreenPart();
23 |
24 | ///
25 | /// 组装输入设备(键鼠)
26 | ///
27 | public abstract void BuildInputPart();
28 |
29 | ///
30 | /// 组装起来
31 | ///
32 | public void Assemble()
33 | {
34 | BuildMainFramePart();
35 | BuildScreenPart();
36 | BuildInputPart();
37 | }
38 |
39 | }
40 |
41 | ///
42 | /// 组装HP电脑
43 | ///
44 | public class AssembleHpComputer : AssembleComputer
45 | {
46 | public override void BuildMainFramePart()
47 | {
48 | Console.WriteLine("组装HP电脑的主板");
49 | }
50 |
51 | public override void BuildScreenPart()
52 | {
53 | Console.WriteLine("组装HP电脑的显示器");
54 | }
55 |
56 | public override void BuildInputPart()
57 | {
58 | Console.WriteLine("组装HP电脑的键盘鼠标");
59 | }
60 | }
61 |
62 | ///
63 | /// 组装HP电脑
64 | ///
65 | public class AssembleDellComputer : AssembleComputer
66 | {
67 | public override void BuildMainFramePart()
68 | {
69 | Console.WriteLine("组装Dell电脑的主板");
70 | }
71 |
72 | public override void BuildScreenPart()
73 | {
74 | Console.WriteLine("组装Dell电脑的显示器");
75 | }
76 |
77 | public override void BuildInputPart()
78 | {
79 | Console.WriteLine("组装Dell电脑的键盘鼠标");
80 | }
81 | }
82 |
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/TemplateMethodPattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace TemplateMethodPattern
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 | //组装HP电脑
14 | Console.WriteLine("开始组织Hp电脑:");
15 | AssembleComputer assembleHpComputer = new AssembleHpComputer();
16 |
17 | assembleHpComputer.Assemble();
18 |
19 | Console.ReadLine();
20 |
21 | //组装DELL电脑
22 | Console.WriteLine("开始组织DELL电脑:");
23 | AssembleComputer assembleDellComputer = new AssembleDellComputer();
24 |
25 | assembleDellComputer.Assemble();
26 |
27 | Console.ReadLine();
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/TemplateMethodPattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过以下
6 | // 特性集控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("TemplateMethodPattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("TemplateMethodPattern")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 使此程序集中的类型
18 | // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
19 | // 则将该类型上的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("2daa8d13-876a-40fa-9f73-fb969aeb2b11")]
24 |
25 | // 程序集的版本信息由下面四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/TemplateMethodPattern/TemplateMethodPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/UpgradeReport.sarif:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json",
3 | "version": "2.1.0",
4 | "runs": [
5 | {
6 | "tool": {
7 | "driver": {
8 | "name": "Back up project",
9 | "semanticVersion": "",
10 | "informationUri": "https://github.com/dotnet/upgrade-assistant#usage",
11 | "rules": [
12 | {
13 | "id": "Microsoft.DotNet.UpgradeAssistant.Steps.Backup.BackupStep",
14 | "fullDescription": {
15 | "text": "Back up the current project to another directory"
16 | }
17 | }
18 | ]
19 | }
20 | },
21 | "results": [
22 | {
23 | "ruleId": "Microsoft.DotNet.UpgradeAssistant.Steps.Backup.BackupStep",
24 | "level": "note",
25 | "message": {
26 | "text": "Complete: Project backed up to D:\\GitHub\\Design-Pattern.backup\\AdapterPattern"
27 | },
28 | "locations": [
29 | {
30 | "physicalLocation": {
31 | "artifactLocation": {
32 | "uri": "file:///D:/GitHub/Design-Pattern.backup/AdapterPattern"
33 | },
34 | "region": {}
35 | }
36 | }
37 | ]
38 | }
39 | ],
40 | "columnKind": "utf16CodeUnits"
41 | },
42 | {
43 | "tool": {
44 | "driver": {
45 | "name": "Add package 'Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers'",
46 | "semanticVersion": "",
47 | "informationUri": "https://github.com/dotnet/upgrade-assistant#usage",
48 | "rules": [
49 | {
50 | "id": "Microsoft.DotNet.UpgradeAssistant.Steps.Packages.PackageUpdaterStep+PackageManipulationStep`1[[Microsoft.DotNet.UpgradeAssistant.NuGetReference, Microsoft.DotNet.UpgradeAssistant.Abstractions, Version=0.4.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]"
51 | }
52 | ]
53 | }
54 | },
55 | "results": [
56 | {
57 | "ruleId": "Microsoft.DotNet.UpgradeAssistant.Steps.Packages.PackageUpdaterStep+PackageManipulationStep`1[[Microsoft.DotNet.UpgradeAssistant.NuGetReference, Microsoft.DotNet.UpgradeAssistant.Abstractions, Version=0.4.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]",
58 | "level": "note",
59 | "message": {
60 | "text": "Complete: Add package 'Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers'"
61 | },
62 | "locations": [
63 | {
64 | "physicalLocation": {
65 | "artifactLocation": {
66 | "uri": "file:///D:/GitHub/Design-Pattern/AdapterPattern/AdapterPattern.csproj"
67 | },
68 | "region": {}
69 | }
70 | }
71 | ]
72 | }
73 | ],
74 | "columnKind": "utf16CodeUnits"
75 | },
76 | {
77 | "tool": {
78 | "driver": {
79 | "name": "Update TFM",
80 | "semanticVersion": "",
81 | "informationUri": "https://github.com/dotnet/upgrade-assistant#usage",
82 | "rules": [
83 | {
84 | "id": "Microsoft.DotNet.UpgradeAssistant.Steps.ProjectFormat.SetTFMStep",
85 | "fullDescription": {
86 | "text": "Update TFM for current project"
87 | }
88 | }
89 | ]
90 | }
91 | },
92 | "results": [
93 | {
94 | "ruleId": "Microsoft.DotNet.UpgradeAssistant.Steps.ProjectFormat.SetTFMStep",
95 | "level": "error",
96 | "message": {
97 | "text": "Failed: Unexpected error applying upgrade step 'Update TFM'\r\nSystem.InvalidOperationException: Project file only supports setting TFM on new style csproj\r\n at Microsoft.DotNet.UpgradeAssistant.Extensions.NuGet.TargetFrameworkMonikerCollection.SetTargetFramework(TargetFrameworkMoniker tfm)\r\n at Microsoft.DotNet.UpgradeAssistant.MSBuild.MSBuildProject.SetTFM(TargetFrameworkMoniker tfm) in /_/src/components/Microsoft.DotNet.UpgradeAssistant.MSBuild/MSBuildProject.File.cs:line 49\r\n at Microsoft.DotNet.UpgradeAssistant.Extensions.TryConvert.SetTFMStep.ApplyImplAsync(IUpgradeContext context, CancellationToken token)\r\n at Microsoft.DotNet.UpgradeAssistant.UpgradeStep.ApplyAsync(IUpgradeContext context, CancellationToken token) in /_/src/common/Microsoft.DotNet.UpgradeAssistant.Abstractions/UpgradeStep.cs:line 178"
98 | },
99 | "locations": [
100 | {
101 | "physicalLocation": {
102 | "artifactLocation": {
103 | "uri": "file:///D:/GitHub/Design-Pattern/AdapterPattern/AdapterPattern.csproj"
104 | },
105 | "region": {}
106 | }
107 | }
108 | ]
109 | }
110 | ],
111 | "columnKind": "utf16CodeUnits"
112 | }
113 | ]
114 | }
--------------------------------------------------------------------------------
/VisitorPattern/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/VisitorPattern/Customer.cs:
--------------------------------------------------------------------------------
1 | using System.Text;
2 | using System.Threading.Tasks;
3 |
4 | namespace VisitorPattern
5 | {
6 |
7 | ///
8 | /// 客户类
9 | ///
10 | public class Customer
11 | {
12 | public int Id { get; set; }
13 |
14 | public string NickName { get; set; }
15 |
16 | public string RealName { get; set; }
17 |
18 | public string Phone { get; set; }
19 |
20 | public string Address { get; set; }
21 |
22 | public string Zip { get; set; }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/VisitorPattern/Distributor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 |
4 | namespace VisitorPattern
5 | {
6 | ///
7 | /// 收发货员
8 | /// 对销售订单,进行发货处理
9 | /// 对退货订单,进行收货处理
10 | ///
11 | public class Distributor : Visitor
12 | {
13 | public int Id { get; set; }
14 | public string Name { get; set; }
15 |
16 | public override void Visit(SaleOrder saleOrder)
17 | {
18 | Console.WriteLine($"开始为销售订单【{saleOrder.Id}】进行发货处理:", saleOrder.Id);
19 |
20 | Console.WriteLine($"一共打包{saleOrder.OrderItems.Sum(line => line.Qty)}件商品。");
21 | Console.WriteLine($"收货人:{saleOrder.Customer.RealName}");
22 | Console.WriteLine($"联系电话:{saleOrder.Customer.Phone}");
23 | Console.WriteLine($"收货地址:{saleOrder.Customer.Address}");
24 | Console.WriteLine($"邮政编码:{saleOrder.Customer.Zip}");
25 |
26 | Console.WriteLine($"订单【{saleOrder.Id}】发货完毕!" );
27 | Console.WriteLine("==========================");
28 | }
29 |
30 | public override void Visit(ReturnOrder returnOrder)
31 | {
32 | Console.WriteLine($"收到来自【{returnOrder.Customer.NickName}】的退货订单【{returnOrder.Id}】,进行退货收货处理:");
33 |
34 | foreach (var item in returnOrder.OrderItems)
35 | {
36 | Console.WriteLine($"【{item.Product.Name}】商品* {item.Qty}" );
37 | }
38 |
39 | Console.WriteLine($"退货订单【{returnOrder.Id}】收货处理完毕!" );
40 | Console.WriteLine("==========================");
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/VisitorPattern/Order.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace VisitorPattern
5 | {
6 | ///
7 | /// 订单抽象类
8 | ///
9 | public abstract class Order
10 | {
11 | public int Id { get; set; }
12 |
13 | public Customer Customer { get; set; }
14 |
15 | public DateTime CreatorDate { get; set; }
16 |
17 | ///
18 | /// 单据品相
19 | ///
20 | public List OrderItems { get; set; }
21 |
22 | public abstract void Accept(Visitor visitor);
23 |
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/VisitorPattern/OrderCenter.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace VisitorPattern
4 | {
5 | ///
6 | /// 订单中心
7 | ///
8 | public class OrderCenter : List
9 | {
10 | public void Accept(Visitor visitor)
11 | {
12 | var iterator = this.GetEnumerator();
13 |
14 | while (iterator.MoveNext())
15 | {
16 | iterator.Current.Accept(visitor);
17 | }
18 | }
19 |
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/VisitorPattern/OrderLine.cs:
--------------------------------------------------------------------------------
1 | namespace VisitorPattern
2 | {
3 | public class OrderLine
4 | {
5 | public int Id { get; set; }
6 |
7 | public Product Product { get; set; }
8 |
9 | public int Qty { get; set; }
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/VisitorPattern/Picker.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace VisitorPattern
4 | {
5 | ///
6 | /// 捡货员
7 | /// 对销售订单,从仓库捡货。
8 | /// 对退货订单,将收到的货品归放回仓库。
9 | ///
10 | public class Picker : Visitor
11 | {
12 | public int Id { get; set; }
13 | public string Name { get; set; }
14 |
15 | public override void Visit(SaleOrder saleOrder)
16 | {
17 | Console.WriteLine($"开始为销售订单【{saleOrder.Id}】进行销售捡货处理:");
18 | foreach (var item in saleOrder.OrderItems)
19 | {
20 | Console.WriteLine($"【{item.Product.Name}】商品* {item.Qty}");
21 | }
22 |
23 | Console.WriteLine($"订单【{saleOrder.Id}】捡货完毕!");
24 |
25 | Console.WriteLine("==========================");
26 | }
27 |
28 | public override void Visit(ReturnOrder returnOrder)
29 | {
30 | Console.WriteLine($"开始为退货订单【{returnOrder.Id}】进行退货捡货处理:");
31 | foreach (var item in returnOrder.OrderItems)
32 | {
33 | Console.WriteLine($"【{item.Product.Name}】商品* {item.Qty}");
34 | }
35 |
36 | Console.WriteLine($"退货订单【{returnOrder.Id}】退货捡货完毕!", returnOrder.Id);
37 | Console.WriteLine("==========================");
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/VisitorPattern/Product.cs:
--------------------------------------------------------------------------------
1 | namespace VisitorPattern
2 | {
3 | ///
4 | /// 产品类
5 | ///
6 | public class Product
7 | {
8 | public int Id { get; set; }
9 |
10 | public string Name { get; set; }
11 |
12 | public virtual decimal Price { get; set; }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/VisitorPattern/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | ///
8 | /// 访问者模式
9 | ///
10 | namespace VisitorPattern
11 | {
12 | class Program
13 | {
14 | static void Main(string[] args)
15 | {
16 | Customer customer = new Customer
17 | {
18 | Id = 1,
19 | NickName = "圣杰",
20 | RealName = "圣杰",
21 | Address = "深圳市南山区",
22 | Phone = "135****9358",
23 | Zip = "518000"
24 | };
25 |
26 | Product productA = new Product { Id = 1, Name = "小米5", Price = 1899 };
27 | Product productB = new Product { Id = 2, Name = "小米5手机防爆膜", Price = 29 };
28 | Product productC = new Product { Id = 3, Name = "小米5手机保护套", Price = 69 };
29 |
30 | OrderLine line1 = new OrderLine { Id = 1, Product = productA, Qty = 1 };
31 | OrderLine line2 = new OrderLine { Id = 1, Product = productB, Qty = 2 };
32 | OrderLine line3 = new OrderLine { Id = 1, Product = productC, Qty = 3 };
33 |
34 | //先买了个小米5和防爆膜
35 | SaleOrder order1 = new SaleOrder { Id = 1, Customer = customer, CreatorDate = DateTime.Now, OrderItems = new List { line1, line2 } };
36 |
37 | //又买了个保护套
38 | SaleOrder order2 = new SaleOrder { Id = 2, Customer = customer, CreatorDate = DateTime.Now, OrderItems = new List { line3 } };
39 |
40 | //把保护套都退了
41 | ReturnOrder returnOrder = new ReturnOrder { Id = 3, Customer = customer, CreatorDate = DateTime.Now, OrderItems = new List { line3 } };
42 |
43 | OrderCenter orderCenter = new OrderCenter { order1, order2, returnOrder };
44 |
45 |
46 | Picker picker = new Picker { Id = 110, Name = "捡货员110" };
47 |
48 | Distributor distributor = new Distributor { Id = 111, Name = "发货货员111" };
49 |
50 | //捡货员访问订单中心
51 | orderCenter.Accept(picker);
52 |
53 | //发货员访问订单中心
54 | orderCenter.Accept(distributor);
55 |
56 | Console.ReadLine();
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/VisitorPattern/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的一般信息由以下
6 | // 控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("VisitorPattern")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("VisitorPattern")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 会使此程序集中的类型
18 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
19 | //请将此类型的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("02f820f2-ce4c-4e47-8ce8-4e7c0a234d42")]
24 |
25 | // 程序集的版本信息由下列四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
33 | // 方法是按如下所示使用“*”: :
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/VisitorPattern/ReturnOrder.cs:
--------------------------------------------------------------------------------
1 | namespace VisitorPattern
2 | {
3 | ///
4 | /// 退货单
5 | ///
6 | public class ReturnOrder : Order
7 | {
8 | public override void Accept(Visitor visitor)
9 | {
10 | visitor.Visit(this);
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/VisitorPattern/SaleOrder.cs:
--------------------------------------------------------------------------------
1 | namespace VisitorPattern
2 | {
3 | ///
4 | /// 销售订单
5 | ///
6 | public class SaleOrder : Order
7 | {
8 | public override void Accept(Visitor visitor)
9 | {
10 | visitor.Visit(this);
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/VisitorPattern/Visitor.cs:
--------------------------------------------------------------------------------
1 | namespace VisitorPattern
2 | {
3 | ///
4 | /// 访问者
5 | ///
6 | public abstract class Visitor
7 | {
8 | public abstract void Visit(SaleOrder saleOrder);
9 | public abstract void Visit(ReturnOrder returnOrder);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/VisitorPattern/VisitorPattern.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net60
4 | Exe
5 | false
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------