├── .gitattributes
├── CSharpDesignPatternDemo
├── CSharpDesignPatternDemo.sln
└── CSharpDesignPatternDemo
│ ├── 01单例模式
│ ├── Singleton.xaml
│ └── Singleton.xaml.cs
│ ├── 02简单工厂模式
│ └── FoodSimpleFactory.cs
│ ├── 03工厂方法模式
│ └── FactoryMethodPattern.cs
│ ├── 04抽象工厂模式
│ └── AbstractFactory.cs
│ ├── 05建造者模式
│ └── BuilderPattern.cs
│ ├── 06原型模式
│ └── PrototypePattern.cs
│ ├── 07适配器模式
│ ├── 对象适配器
│ │ └── AdapterPattern2.cs
│ └── 类适配器
│ │ └── AdapterPattern.cs
│ ├── 08桥接模式
│ └── BridgePattern.cs
│ ├── 09装饰者模式
│ └── DecoratorPattern.cs
│ ├── 10组合模式
│ ├── 安全式的组合模式
│ │ └── CompositePattern2.cs
│ └── 透明式的组合模式
│ │ └── CompositePattern.cs
│ ├── 11外观模式
│ └── FacadePattern.cs
│ ├── 12享元模式
│ └── FlyweightPattern.cs
│ ├── 13代理模式
│ └── ProxyPattern.cs
│ ├── 14模板方法
│ └── TemplateMethod.cs
│ ├── 15命令模式
│ └── CommandPattern.cs
│ ├── 16迭代器模式
│ └── IteratorPattern.cs
│ ├── 17观察者模式
│ └── ObserverPattern.cs
│ ├── 18中介者模式
│ └── MediatorPattern.cs
│ ├── 19状态者模式
│ └── StatePattern.cs
│ ├── 20策略模式
│ └── StrategyPattern.cs
│ ├── 21责任链模式
│ └── ChainofResponsibility.cs
│ ├── 22访问者模式
│ └── VistorPattern.cs
│ ├── 23备忘录模式
│ └── MementoPattern.cs
│ ├── App.xaml
│ ├── App.xaml.cs
│ ├── CSharpDesignPatternDemo.csproj
│ ├── MainWindow.xaml
│ ├── MainWindow.xaml.cs
│ ├── Properties
│ ├── AssemblyInfo.cs
│ ├── Resources.Designer.cs
│ ├── Resources.resx
│ ├── Settings.Designer.cs
│ └── Settings.settings
│ └── bin
│ └── Debug
│ ├── CSharpDesignPatternDemo.exe
│ ├── CSharpDesignPatternDemo.pdb
│ ├── CSharpDesignPatternDemo.vshost.exe
│ └── CSharpDesignPatternDemo.vshost.exe.manifest
├── README.md
└── 项目说明.txt
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 | bin/
4 | obj/
5 | Debug/
6 | Release/
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 14
4 | VisualStudioVersion = 14.0.25420.1
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpDesignPatternDemo", "CSharpDesignPatternDemo\CSharpDesignPatternDemo.csproj", "{AA113DB3-4117-4526-9197-11E33209CBFB}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {AA113DB3-4117-4526-9197-11E33209CBFB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {AA113DB3-4117-4526-9197-11E33209CBFB}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {AA113DB3-4117-4526-9197-11E33209CBFB}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {AA113DB3-4117-4526-9197-11E33209CBFB}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/01单例模式/Singleton.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/01单例模式/Singleton.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Windows;
6 | using System.Windows.Controls;
7 | using System.Windows.Data;
8 | using System.Windows.Documents;
9 | using System.Windows.Input;
10 | using System.Windows.Media;
11 | using System.Windows.Media.Imaging;
12 | using System.Windows.Shapes;
13 |
14 | namespace CSharpDesignPatternDemo
15 | {
16 | ///
17 | /// Singleton.xaml 的交互逻辑
18 | ///
19 | public partial class Singleton : Window
20 | {
21 | public Singleton()
22 | {
23 | InitializeComponent();
24 | }
25 |
26 | #region 单线程处理,单例模式
27 | ///
28 | /// 定义一个静态变量来保存类的实例
29 | ///
30 | private static Singleton uniqueInstance;
31 | ///
32 | /// 定义公有方法提供一个全局的访问点,同时你也可以定义公有属性变量来提供全局访问点
33 | ///
34 | ///
35 | public static Singleton GetInstance()
36 | {
37 | if (uniqueInstance == null)
38 | {
39 | uniqueInstance = new Singleton();
40 | }
41 | return uniqueInstance;
42 | }
43 | #endregion
44 |
45 |
46 | #region 多线程处理,单例模式,推荐使用
47 | ///
48 | /// 定义一个静态变量来保存类的实例
49 | ///
50 | private static Singleton uniqueInstance2;
51 | ///
52 | /// 定义一个标识确保线程同步
53 | ///
54 | private static readonly object locker = new object();
55 | ///
56 | /// 定义公有方法提供一个全局的访问点,同时你也可以定义公有属性变量来提供全局访问点
57 | ///
58 | ///
59 | public static Singleton GetInstance2()
60 | {
61 | // 当第一个线程运行到这里时,此时会对locker对象 "加锁",
62 | // 当第二个线程运行该方法时,首先检测到locker对象为"加锁"状态,该线程就会挂起等待第一个线程解锁
63 | // lock语句运行完之后(即线程运行完之后)会对该对象"解锁"
64 | // 双重锁定只需要一句判断就可以了
65 | if (uniqueInstance2==null)
66 | {
67 | lock(locker)
68 | {
69 | if (uniqueInstance2 == null)
70 | {
71 | uniqueInstance2 = new Singleton();
72 | }
73 | }
74 | }
75 | return uniqueInstance2;
76 | }
77 | #endregion
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/02简单工厂模式/FoodSimpleFactory.cs:
--------------------------------------------------------------------------------
1 | using CSharpDesignPatternDemo;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using static CSharpDesignPatternDemo.FoodSimpleFactoryClass;
7 |
8 | namespace CSharpDesignPatternDemo
9 | {
10 | public class FoodSimpleFactory
11 | {
12 | FoodSimpleFactory()
13 | {
14 | //客户想吃西红柿炒鸡蛋
15 | Food food1 = FoodSimpleFactoryClassMethod.CreateFood("西红柿炒鸡蛋");
16 | food1.Print();
17 |
18 | //客户想再点一个土豆肉丝
19 | Food food2 = FoodSimpleFactoryClassMethod.CreateFood("土豆肉丝");
20 | food2.Print();
21 |
22 | Console.Read();
23 | }
24 | }
25 |
26 | public class FoodSimpleFactoryClass
27 | {
28 | ///
29 | /// 菜抽象类
30 | ///
31 | public abstract class Food
32 | {
33 | //输出点了什么菜
34 | public abstract void Print();
35 | }
36 |
37 | ///
38 | /// 西红柿炒鸡蛋这道菜
39 | ///
40 | public class TomatoScrambleEggs : Food
41 | {
42 | public override void Print()
43 | {
44 | Console.WriteLine("一份西红柿炒鸡蛋!");
45 | }
46 | }
47 |
48 | ///
49 | /// 土豆肉丝这道菜
50 | ///
51 | public class ShreddedPorkWithPotatoes : Food
52 | {
53 | public override void Print()
54 | {
55 | Console.WriteLine("一份土豆肉丝!");
56 | }
57 | }
58 | }
59 |
60 | ///
61 | /// 简单工厂类,负责 炒菜
62 | ///
63 | public class FoodSimpleFactoryClassMethod
64 | {
65 | public static Food CreateFood(string type)
66 | {
67 | Food food = null;
68 | if (type == "土豆肉丝")
69 | {
70 | food = new ShreddedPorkWithPotatoes();
71 | }
72 | else if (type == "西红柿炒鸡蛋")
73 | {
74 | food = new TomatoScrambleEggs();
75 | }
76 |
77 | return food;
78 | }
79 |
80 |
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/03工厂方法模式/FactoryMethodPattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using static CSharpDesignPatternDemo.FactoryMethodPatternClass;
6 |
7 | namespace CSharpDesignPatternDemo
8 | {
9 | public class FactoryMethodPattern
10 | {
11 | FactoryMethodPattern()
12 | {
13 | // 初始化做菜的两个工厂()
14 | Creator shreddedPorkWithPotatoesFactory = new ShreddedPorkWithPotatoesFactory();
15 | Creator tomatoScrambledEggsFactory = new TomatoScrambledEggsFactory();
16 |
17 | // 开始做西红柿炒蛋
18 | Food tomatoScrambleEggs = tomatoScrambledEggsFactory.CreateFoodFactory();
19 | tomatoScrambleEggs.Print();
20 |
21 | //开始做土豆肉丝
22 | Food shreddedPorkWithPotatoes = shreddedPorkWithPotatoesFactory.CreateFoodFactory();
23 | shreddedPorkWithPotatoes.Print();
24 |
25 | // 如果客户又想点肉末茄子了
26 | // 再另外初始化一个肉末茄子工厂
27 | Creator minceMeatEggplantFactor = new MincedMeatEggplantFactory();
28 |
29 | // 利用肉末茄子工厂来创建肉末茄子这道菜
30 | Food minceMeatEggplant = minceMeatEggplantFactor.CreateFoodFactory();
31 | minceMeatEggplant.Print();
32 |
33 | Console.Read();
34 | }
35 | }
36 |
37 | public class FactoryMethodPatternClass
38 | {
39 | public abstract class Food
40 | {
41 | public abstract void Print();
42 | }
43 |
44 | ///
45 | /// 西红柿炒鸡蛋这道菜
46 | ///
47 | public class TomatoScrambledEggs : Food
48 | {
49 | public override void Print()
50 | {
51 | Console.WriteLine("西红柿炒蛋好了!");
52 | }
53 | }
54 |
55 | ///
56 | /// 土豆肉丝这道菜
57 | ///
58 | public class ShreddedPorkWithPotatoes : Food
59 | {
60 | public override void Print()
61 | {
62 | Console.WriteLine("土豆肉丝好了");
63 | }
64 | }
65 |
66 | ///
67 | /// 抽象工厂类
68 | ///
69 | public abstract class Creator
70 | {
71 | // 工厂方法
72 | public abstract Food CreateFoodFactory();
73 | }
74 |
75 | ///
76 | /// 西红柿炒蛋工厂类
77 | ///
78 | public class TomatoScrambledEggsFactory : Creator
79 | {
80 | ///
81 | /// 负责创建西红柿炒蛋这道菜
82 | ///
83 | ///
84 | public override Food CreateFoodFactory()
85 | {
86 | return new TomatoScrambledEggs();
87 | }
88 | }
89 |
90 | ///
91 | /// 肉末茄子这道菜
92 | ///
93 | public class MincedMeatEggplant : Food
94 | {
95 | ///
96 | /// 重写抽象类中的方法
97 | ///
98 | public override void Print()
99 | {
100 | Console.WriteLine("肉末茄子好了");
101 | }
102 | }
103 | ///
104 | /// 肉末茄子工厂类,负责创建肉末茄子这道菜
105 | ///
106 | public class MincedMeatEggplantFactory : Creator
107 | {
108 | ///
109 | /// 负责创建肉末茄子这道菜
110 | ///
111 | ///
112 | public override Food CreateFoodFactory()
113 | {
114 | return new MincedMeatEggplant();
115 | }
116 | }
117 |
118 | ///
119 | /// 土豆肉丝工厂类
120 | ///
121 | public class ShreddedPorkWithPotatoesFactory : Creator
122 | {
123 | ///
124 | /// 负责创建土豆肉丝这道菜
125 | ///
126 | ///
127 | public override Food CreateFoodFactory()
128 | {
129 | return new ShreddedPorkWithPotatoes();
130 | }
131 | }
132 | }
133 |
134 |
135 | }
136 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/04抽象工厂模式/AbstractFactory.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using static CSharpDesignPatternDemo.AbstractFactoryClass;
6 |
7 | namespace CSharpDesignPatternDemo
8 | {
9 | class AbstractFactoryCilent
10 | {
11 | public AbstractFactoryCilent()
12 | {
13 | AbstractFactory nanChangFactory = new NanChangFactory();
14 | YaBo nanChangYabo = nanChangFactory.CreateYabo();
15 | nanChangYabo.Print();
16 | YaJia nanChangYajia = nanChangFactory.CreateYaJia();
17 | nanChangYajia.Print();
18 |
19 | AbstractFactory shangHaiFactory = new ShangHaiFactory();
20 | YaBo shangHaiYabo = shangHaiFactory.CreateYabo();
21 | shangHaiYabo.Print();
22 | YaJia shangHaiYajia = shangHaiFactory.CreateYaJia();
23 | shangHaiYajia.Print();
24 |
25 | //新增湖南
26 | AbstractFactory huNanFactory = new HuNanFactory();
27 | YaBo huNanYabo = huNanFactory.CreateYabo();
28 | huNanYabo.Print();
29 | YaJia huNanYajia = huNanFactory.CreateYaJia();
30 | huNanYajia.Print();
31 | }
32 |
33 | }
34 |
35 | public class AbstractFactoryClass
36 | {
37 | public abstract class AbstractFactory
38 | {
39 | public abstract YaBo CreateYabo();
40 | public abstract YaJia CreateYaJia();
41 | }
42 |
43 | public abstract class YaBo
44 | {
45 | public abstract void Print();
46 | }
47 |
48 | public abstract class YaJia
49 | {
50 | public abstract void Print();
51 | }
52 |
53 | public class NanChangFactory:AbstractFactory
54 | {
55 | public override YaBo CreateYabo()
56 | {
57 | return new NanChangYaBo();
58 | }
59 |
60 | public override YaJia CreateYaJia()
61 | {
62 | return new NanChangYaJia();
63 | }
64 | }
65 |
66 | public class ShangHaiFactory : AbstractFactory
67 | {
68 | public override YaBo CreateYabo()
69 | {
70 | return new ShangHaiYaBo();
71 | }
72 |
73 | public override YaJia CreateYaJia()
74 | {
75 | return new ShangHaiYaJia();
76 | }
77 | }
78 | //新增湖南
79 | public class HuNanFactory:AbstractFactory
80 | {
81 | public override YaBo CreateYabo()
82 | {
83 | return new HuNanYaBo();
84 | }
85 |
86 | public override YaJia CreateYaJia()
87 | {
88 | return new HuNanYaJia();
89 | }
90 | }
91 |
92 | public class NanChangYaBo : YaBo
93 | {
94 | public override void Print()
95 | {
96 | Console.WriteLine("南昌的鸭脖");
97 | }
98 | }
99 |
100 | public class NanChangYaJia:YaJia
101 | {
102 | public override void Print()
103 | {
104 | Console.WriteLine("南昌的鸭架子");
105 | }
106 | }
107 | public class ShangHaiYaBo : YaBo
108 | {
109 | public override void Print()
110 | {
111 | Console.WriteLine("上海的鸭脖");
112 | }
113 | }
114 | //新增湖南
115 | public class ShangHaiYaJia : YaJia
116 | {
117 | public override void Print()
118 | {
119 | Console.WriteLine("上海的鸭架子");
120 | }
121 | }
122 |
123 | public class HuNanYaBo : YaBo
124 | {
125 | public override void Print()
126 | {
127 | Console.WriteLine("湖南的鸭脖");
128 | }
129 | }
130 |
131 | public class HuNanYaJia : YaJia
132 | {
133 | public override void Print()
134 | {
135 | Console.WriteLine("湖南的鸭架子");
136 | }
137 | }
138 | }
139 |
140 | }
141 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/05建造者模式/BuilderPattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpDesignPatternDemo
7 | {
8 | public class BuilderPattern
9 | {
10 | BuilderPattern()
11 | {
12 | // 客户找到电脑城老板说要买电脑,这里要装两台电脑
13 | // 创建指挥者和构造者
14 | Director director = new Director();
15 | Builder b1 = new ConcreteBuilder1();
16 | Builder b2 = new ConcreteBuilder2();
17 |
18 | // 老板叫员工去组装第一台电脑
19 | director.Construct(b1);
20 |
21 | // 组装完,组装人员搬来组装好的电脑
22 | Computer computer1 = b1.GetComputer();
23 | computer1.Show();
24 |
25 | // 老板叫员工去组装第二台电脑
26 | director.Construct(b2);
27 | Computer computer2 = b2.GetComputer();
28 | computer2.Show();
29 |
30 | Console.Read();
31 | }
32 | }
33 |
34 | ///
35 | /// 小王和小李难道会自愿地去组装嘛,谁不想休息的,这必须有一个人叫他们去组装才会去的
36 | /// 这个人当然就是老板了,也就是建造者模式中的指挥者
37 | /// 指挥创建过程类
38 | ///
39 | public class Director
40 | {
41 | // 组装电脑
42 | public void Construct(Builder builder)
43 | {
44 | builder.BuildPartCPU();
45 | builder.BuildPartMainBoard();
46 | }
47 | }
48 | ///
49 | /// 电脑类
50 | ///
51 | public class Computer
52 | {
53 | // 电脑组件集合
54 | private IList parts = new List();
55 | // 把单个组件添加到电脑组件集合中
56 | public void Add(string part)
57 | {
58 | parts.Add(part);
59 | }
60 |
61 | public void Show()
62 | {
63 | Console.WriteLine("电脑开始在组装.......");
64 | foreach (string part in parts)
65 | {
66 | Console.WriteLine("组件" + part + "已装好");
67 | }
68 |
69 | Console.WriteLine("电脑组装好了");
70 | }
71 | }
72 |
73 | ///
74 | /// 抽象建造者,这个场景下为 "组装人" ,这里也可以定义为接口
75 | ///
76 | public abstract class Builder
77 | {
78 | // 装CPU
79 | public abstract void BuildPartCPU();
80 | // 装主板
81 | public abstract void BuildPartMainBoard();
82 | // 当然还有装硬盘,电源等组件,这里省略
83 |
84 | // 获得组装好的电脑
85 | public abstract Computer GetComputer();
86 | }
87 |
88 | public class ConcreteBuilder1:Builder
89 | {
90 | Computer computer = new Computer();
91 | public override void BuildPartCPU()
92 | {
93 | computer.Add("CPU1");
94 | }
95 |
96 | public override void BuildPartMainBoard()
97 | {
98 | computer.Add("Main board1");
99 | }
100 |
101 | public override Computer GetComputer()
102 | {
103 | return computer;
104 | }
105 | }
106 |
107 | ///
108 | /// 具体创建者,具体的某个人为具体创建者,例如:装机小李啊
109 | /// 又装另一台电脑了
110 | ///
111 | public class ConcreteBuilder2 : Builder
112 | {
113 | Computer computer = new Computer();
114 | public override void BuildPartCPU()
115 | {
116 | computer.Add("CPU2");
117 | }
118 |
119 | public override void BuildPartMainBoard()
120 | {
121 | computer.Add("Main board2");
122 | }
123 |
124 | public override Computer GetComputer()
125 | {
126 | return computer;
127 | }
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/06原型模式/PrototypePattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpDesignPatternDemo
7 | {
8 | ///火影忍者中鸣人的影分身和孙悟空的的变都是原型模式
9 | public class PrototypePattern
10 | {
11 | PrototypePattern()
12 | {
13 | // 孙悟空 原型
14 | MonkeyKingPrototype prototypeMonkeyKing = new ConcretePrototype("MonkeyKing");
15 |
16 | // 变一个
17 | MonkeyKingPrototype cloneMonkeyKing = prototypeMonkeyKing.Clone() as ConcretePrototype;
18 | Console.WriteLine("Cloned1:\t" + cloneMonkeyKing.Id);
19 |
20 | // 变两个
21 | MonkeyKingPrototype cloneMonkeyKing2 = prototypeMonkeyKing.Clone() as ConcretePrototype;
22 | Console.WriteLine("Cloned2:\t" + cloneMonkeyKing2.Id);
23 | Console.ReadLine();
24 | }
25 | }
26 |
27 | ///
28 | /// 孙悟空原型
29 | ///
30 | public abstract class MonkeyKingPrototype
31 | {
32 | public string Id { get; set; }
33 |
34 | public MonkeyKingPrototype(string id)
35 | {
36 | this.Id = id;
37 | }
38 | // 克隆方法,即孙大圣说“变”
39 | public abstract MonkeyKingPrototype Clone();
40 | }
41 |
42 | public class ConcretePrototype:MonkeyKingPrototype
43 | {
44 | public ConcretePrototype(string id) : base(id)
45 | { }
46 |
47 | ///
48 | /// 浅拷贝
49 | ///
50 | ///
51 | public override MonkeyKingPrototype Clone()
52 | {
53 | // 调用MemberwiseClone方法实现的是浅拷贝,另外还有深拷贝
54 | return (MonkeyKingPrototype)this.MemberwiseClone();
55 | }
56 | }
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/07适配器模式/对象适配器/AdapterPattern2.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpDesignPatternDemo
7 | {
8 | public class AdapterPattern2
9 | {
10 | AdapterPattern2()
11 | {
12 | // 现在客户端可以通过电适配要使用2个孔的插头了
13 | ThreeHole threehole = new PowerAdapter2();
14 | threehole.Request();
15 | Console.ReadLine();
16 | }
17 | }
18 |
19 | ///
20 | /// 三个孔的插头,也就是适配器模式中的目标(Target)角色
21 | ///
22 | public class ThreeHole
23 | {
24 | // 客户端需要的方法
25 | public virtual void Request()
26 | {
27 | // 可以把一般实现放在这里
28 | }
29 | }
30 |
31 | ///
32 | /// 两个孔的插头,源角色——需要适配的类
33 | ///
34 | public class TwoHole2
35 | {
36 | public void SpecificRequest()
37 | {
38 | Console.WriteLine("我是两个孔的插头");
39 | }
40 | }
41 |
42 | ///
43 | /// 适配器类,这里适配器类没有TwoHole类,
44 | /// 而是引用了TwoHole对象,所以是对象的适配器模式的实现
45 | ///
46 | public class PowerAdapter2 : ThreeHole
47 | {
48 | // 引用两个孔插头的实例,从而将客户端与TwoHole联系起来
49 | public TwoHole2 twoholeAdaptee = new TwoHole2();
50 |
51 | ///
52 | /// 实现三个孔插头接口方法
53 | ///
54 | public override void Request()
55 | {
56 | twoholeAdaptee.SpecificRequest();
57 | }
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/07适配器模式/类适配器/AdapterPattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpDesignPatternDemo
7 | {
8 | /// 这里以插座和插头的例子来诠释适配器模式
9 | /// 现在我们买的电器插头是2个孔,但是我们买的插座只有3个孔的
10 | /// 这是我们想把电器插在插座上的话就需要一个电适配器
11 | public class AdapterPattern
12 | {
13 | AdapterPattern()
14 | {
15 | // 现在客户端可以通过电适配要使用2个孔的插头了
16 | IThreeHole threehole = new PowerAdapter();
17 | threehole.Request();
18 | Console.ReadLine();
19 | }
20 | }
21 |
22 | ///
23 | /// 三个孔的插头,也就是适配器模式中的目标角色
24 | ///
25 | public interface IThreeHole
26 | {
27 | void Request();
28 | }
29 |
30 | ///
31 | /// 两个孔的插头,源角色——需要适配的类
32 | ///
33 | public abstract class TwoHole
34 | {
35 | public void SpecificRequest()
36 | {
37 | Console.WriteLine("我是两个孔的插头");
38 | }
39 | }
40 |
41 | ///
42 | /// 适配器类,接口要放在类的后面
43 | /// 适配器类提供了三个孔插头的行为,但其本质是调用两个孔插头的方法
44 | ///
45 | public class PowerAdapter : TwoHole, IThreeHole
46 | {
47 | ///
48 | /// 实现三个孔插头接口方法
49 | ///
50 | public void Request()
51 | {
52 | // 调用两个孔插头方法
53 | this.SpecificRequest();
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/08桥接模式/BridgePattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using static CSharpDesignPatternDemo.Implementation;
6 |
7 | namespace CSharpDesignPatternDemo
8 | {
9 | public class BridgePattern
10 | {
11 | ///
12 | /// 以电视机遥控器的例子来演示桥接模式
13 | ///
14 | BridgePattern()
15 | {
16 | // 创建一个遥控器
17 | RemoteControl remoteControl = new ConcreteRemote();
18 | // 长虹电视机
19 | remoteControl.Implementor = new ChangHong();
20 | remoteControl.On();
21 | remoteControl.SetChannel();
22 | remoteControl.Off();
23 | Console.WriteLine();
24 |
25 | // 三星牌电视机
26 | remoteControl.Implementor = new Samsung();
27 | remoteControl.On();
28 | remoteControl.SetChannel();
29 | remoteControl.Off();
30 | Console.Read();
31 | }
32 | }
33 |
34 | public class RemoteControl
35 | {
36 | ///
37 | /// 字段
38 | ///
39 | private TV implementor;
40 | // 属性
41 | public TV Implementor
42 | {
43 | get { return implementor; }
44 | set { implementor = value; }
45 | }
46 | ///
47 | /// 开电视机,这里抽象类中不再提供实现了,而是调用实现类中的实现
48 | ///
49 | public virtual void On()
50 | {
51 | implementor.On();
52 | }
53 | ///
54 | /// 关电视机
55 | ///
56 | public virtual void Off()
57 | {
58 | implementor.Off();
59 | }
60 | ///
61 | /// 换频道
62 | ///
63 | public virtual void SetChannel()
64 | {
65 | implementor.tuneChannel();
66 | }
67 | }
68 | ///
69 | /// 具体遥控器
70 | ///
71 | public class ConcreteRemote:RemoteControl
72 | {
73 | public override void SetChannel()
74 | {
75 | Console.WriteLine("---------------------");
76 | base.SetChannel();
77 | Console.WriteLine("---------------------");
78 | }
79 | }
80 |
81 | public class Implementation
82 | {
83 | ///
84 | /// 电视机,提供抽象方法
85 | ///
86 | public abstract class TV
87 | {
88 | public abstract void On();
89 | public abstract void Off();
90 | public abstract void tuneChannel();
91 | }
92 |
93 | ///
94 | /// 长虹牌电视机,重写基类的抽象方法
95 | /// 提供具体的实现
96 | ///
97 | public class ChangHong:TV
98 | {
99 | public override void On()
100 | {
101 | Console.WriteLine("长虹牌电视机已经打开了");
102 | }
103 |
104 | public override void Off()
105 | {
106 | Console.WriteLine("长虹牌电视机已经关掉了");
107 | }
108 |
109 | public override void tuneChannel()
110 | {
111 | Console.WriteLine("长虹牌电视机换频道");
112 | }
113 | }
114 |
115 | ///
116 | /// 三星牌电视机,重写基类的抽象方法
117 | ///
118 | public class Samsung : TV
119 | {
120 | public override void On()
121 | {
122 | Console.WriteLine("三星牌电视机已经打开了");
123 | }
124 |
125 | public override void Off()
126 | {
127 | Console.WriteLine("三星牌电视机已经关掉了");
128 | }
129 |
130 | public override void tuneChannel()
131 | {
132 | Console.WriteLine("三星牌电视机换频道");
133 | }
134 | }
135 | }
136 |
137 |
138 | }
139 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/09装饰者模式/DecoratorPattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpDesignPatternDemo
7 | {
8 | public class DecoratorPattern
9 | {
10 | public DecoratorPattern()
11 | {
12 | // 我买了个苹果手机
13 | Phone phone = new ApplePhone();
14 |
15 | // 现在想贴膜了
16 | Decorator applePhoneWithSticker = new Sticker(phone);
17 | // 扩展贴膜行为
18 | applePhoneWithSticker.Print();
19 | Console.WriteLine("----------------------\n");
20 |
21 | // 现在我想有挂件了
22 | Decorator applePhoneWithAccessories = new Accessories(phone);
23 | // 扩展手机挂件行为
24 | applePhoneWithAccessories.Print();
25 | Console.WriteLine("----------------------\n");
26 |
27 | // 现在我同时有贴膜和手机挂件了
28 | Sticker sticker = new Sticker(phone);
29 | Accessories applePhoneWithAccessoriesAndSticker = new Accessories(sticker);
30 | applePhoneWithAccessoriesAndSticker.Print();
31 | Console.ReadLine();
32 | }
33 | }
34 |
35 | public abstract class Phone
36 | {
37 | public abstract void Print();
38 | }
39 |
40 | public class ApplePhone : Phone
41 | {
42 | public override void Print()
43 | {
44 | Console.WriteLine("开始执行具体的对象——苹果手机");
45 | }
46 | }
47 |
48 | public abstract class Decorator:Phone
49 | {
50 | private Phone phone;
51 | public Decorator(Phone p)
52 | {
53 | this.phone = p;
54 | }
55 | public override void Print()
56 | {
57 | if(phone!=null)
58 | {
59 | phone.Print();
60 | }
61 | }
62 | }
63 | ///
64 | /// 贴膜,即具体装饰者
65 | ///
66 | public class Sticker:Decorator
67 | {
68 | public Sticker(Phone p):base(p)
69 | {
70 |
71 | }
72 |
73 | public override void Print()
74 | {
75 | base.Print();
76 | //添加新行为
77 | AddSticker();
78 | }
79 |
80 | private void AddSticker()
81 | {
82 | Console.WriteLine("现在苹果手机有贴膜了");
83 | }
84 | }
85 | ///
86 | /// 手机挂机
87 | ///
88 | public class Accessories:Decorator
89 | {
90 | public Accessories(Phone p):base(p)
91 | {
92 |
93 | }
94 | public override void Print()
95 | {
96 | base.Print();
97 | //添加新的行为
98 | AddAccessories();
99 | }
100 | //新的行为方法
101 | private void AddAccessories()
102 | {
103 | Console.WriteLine("现在苹果手机有漂亮的挂件了");
104 | }
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/10组合模式/安全式的组合模式/CompositePattern2.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpDesignPatternDemo
7 | {
8 | public class CompositePattern2
9 | {
10 | CompositePattern2()
11 | {
12 | ComplexGraphics complexGraphics = new ComplexGraphics("一个复杂图形和两条线段组成的复杂图形");
13 | complexGraphics.Add(new Line("线段A"));
14 | ComplexGraphics CompositeCG = new ComplexGraphics("一个圆和一条线组成的复杂图形");
15 | CompositeCG.Add(new Circle("圆"));
16 | CompositeCG.Add(new Circle("线段B"));
17 | complexGraphics.Add(CompositeCG);
18 | Line l = new Line("线段C");
19 | complexGraphics.Add(l);
20 |
21 | // 显示复杂图形的画法
22 | Console.WriteLine("复杂图形的绘制如下:");
23 | Console.WriteLine("---------------------");
24 | complexGraphics.Draw();
25 | Console.WriteLine("复杂图形绘制完成");
26 | Console.WriteLine("---------------------");
27 | Console.WriteLine();
28 |
29 | // 移除一个组件再显示复杂图形的画法
30 | complexGraphics.Remove(l);
31 | Console.WriteLine("移除线段C后,复杂图形的绘制如下:");
32 | Console.WriteLine("---------------------");
33 | complexGraphics.Draw();
34 | Console.WriteLine("复杂图形绘制完成");
35 | Console.WriteLine("---------------------");
36 | Console.Read();
37 | }
38 | }
39 |
40 | ///
41 | /// 图形抽象类
42 | ///
43 | public abstract class Graphics2
44 | {
45 | public string Name { get; set; }
46 | public Graphics2(string name)
47 | {
48 | this.Name = name;
49 | }
50 |
51 | public abstract void Draw();
52 |
53 | }
54 |
55 | public class Line2 : Graphics2
56 | {
57 | public Line2(string name) : base(name)
58 | {
59 |
60 | }
61 | //重写父类抽象方法
62 | public override void Draw()
63 | {
64 | Console.WriteLine("画 " + Name);
65 | }
66 |
67 | }
68 |
69 | public class Circle2 : Graphics2
70 | {
71 | public Circle2(string name) : base(name)
72 | {
73 |
74 | }
75 |
76 | public override void Draw()
77 | {
78 | Console.WriteLine("画 " + Name);
79 | }
80 |
81 | }
82 | ///
83 | /// 复杂图形,由一些简单图形组成,这里假设该复杂图形由一个圆两条线组成的复杂图形
84 | ///
85 | public class ComplexGraphics2 : Graphics2
86 | {
87 | private List complexGraphicsList = new List();
88 |
89 | public ComplexGraphics2(string name) : base(name)
90 | { }
91 |
92 | ///
93 | /// 复杂图形的画法
94 | ///
95 | public override void Draw()
96 | {
97 | foreach (Graphics2 g in complexGraphicsList)
98 | {
99 |
100 | g.Draw();
101 | }
102 | }
103 |
104 | public void Add(Graphics2 g)
105 | {
106 | complexGraphicsList.Add(g);
107 | }
108 |
109 | public void Remove(Graphics2 g)
110 | {
111 | complexGraphicsList.Remove(g);
112 | }
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/10组合模式/透明式的组合模式/CompositePattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpDesignPatternDemo
7 | {
8 | public class CompositePattern
9 | {
10 | CompositePattern()
11 | {
12 | ComplexGraphics complexGraphics = new ComplexGraphics("一个复杂图形和两条线段组成的复杂图形");
13 | complexGraphics.Add(new Line("线段A"));
14 | ComplexGraphics CompositeCG = new ComplexGraphics("一个圆和一条线组成的复杂图形");
15 | CompositeCG.Add(new Circle("圆"));
16 | CompositeCG.Add(new Circle("线段B"));
17 | complexGraphics.Add(CompositeCG);
18 | Line l = new Line("线段C");
19 | complexGraphics.Add(l);
20 |
21 | // 显示复杂图形的画法
22 | Console.WriteLine("复杂图形的绘制如下:");
23 | Console.WriteLine("---------------------");
24 | complexGraphics.Draw();
25 | Console.WriteLine("复杂图形绘制完成");
26 | Console.WriteLine("---------------------");
27 | Console.WriteLine();
28 |
29 | // 移除一个组件再显示复杂图形的画法
30 | complexGraphics.Remove(l);
31 | Console.WriteLine("移除线段C后,复杂图形的绘制如下:");
32 | Console.WriteLine("---------------------");
33 | complexGraphics.Draw();
34 | Console.WriteLine("复杂图形绘制完成");
35 | Console.WriteLine("---------------------");
36 | Console.Read();
37 | }
38 | }
39 |
40 | ///
41 | /// 图形抽象类
42 | ///
43 | public abstract class Graphics
44 | {
45 | public string Name { get; set; }
46 | public Graphics(string name)
47 | {
48 | this.Name = name;
49 | }
50 |
51 | public abstract void Draw();
52 | public abstract void Add(Graphics g);
53 | public abstract void Remove(Graphics g);
54 | }
55 |
56 | public class Line:Graphics
57 | {
58 | public Line(string name):base(name)
59 | {
60 |
61 | }
62 | //重写父类抽象方法
63 | public override void Draw()
64 | {
65 | Console.WriteLine("画 " + Name);
66 | }
67 |
68 | // 因为简单图形在添加或移除其他图形,所以简单图形Add或Remove方法没有任何意义
69 | // 如果客户端调用了简单图形的Add或Remove方法将会在运行时抛出异常
70 | // 我们可以在客户端捕获该类移除并处理
71 | public override void Add(Graphics g)
72 | {
73 | throw new Exception("不能向简单图形Line添加其他图形");
74 | }
75 |
76 | public override void Remove(Graphics g)
77 | {
78 | throw new Exception("不能向简单图形Line移除其他图形");
79 | }
80 | }
81 |
82 | public class Circle:Graphics
83 | {
84 | public Circle(string name):base(name)
85 | {
86 |
87 | }
88 |
89 | public override void Draw()
90 | {
91 | Console.WriteLine("画 " + Name);
92 | }
93 |
94 | public override void Add(Graphics g)
95 | {
96 | throw new Exception("不能向简单图形Circle添加其他图形");
97 | }
98 |
99 | public override void Remove(Graphics g)
100 | {
101 | throw new Exception("不能向简单图形Circle移除其他图形");
102 | }
103 | }
104 | ///
105 | /// 复杂图形,由一些简单图形组成,这里假设该复杂图形由一个圆两条线组成的复杂图形
106 | ///
107 | public class ComplexGraphics:Graphics
108 | {
109 | private List complexGraphicsList = new List();
110 |
111 | public ComplexGraphics(string name):base(name)
112 | { }
113 |
114 | ///
115 | /// 复杂图形的画法
116 | ///
117 | public override void Draw()
118 | {
119 | foreach (Graphics g in complexGraphicsList)
120 | {
121 |
122 | g.Draw();
123 | }
124 | }
125 |
126 | public override void Add(Graphics g)
127 | {
128 | complexGraphicsList.Add(g);
129 | }
130 |
131 | public override void Remove(Graphics g)
132 | {
133 | complexGraphicsList.Remove(g);
134 | }
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/11外观模式/FacadePattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpDesignPatternDemo
7 | {
8 | public class FacadePattern
9 | {
10 | FacadePattern()
11 | {
12 |
13 | }
14 | }
15 |
16 | ///
17 | /// 外观类
18 | ///
19 | public class RegistrationFacade
20 | {
21 | private RegisterCourse registerCorse;
22 | private NotifyStudent notifyStudent;
23 |
24 | public RegistrationFacade()
25 | {
26 | registerCorse = new RegisterCourse();
27 | notifyStudent = new NotifyStudent();
28 | }
29 |
30 | public bool RegisterCourse(string courseName,string studentName)
31 | {
32 | if(!registerCorse.CheckAvailable(courseName))
33 | {
34 | return false;
35 | }
36 | return notifyStudent.Notify(studentName);
37 | }
38 | }
39 |
40 | #region 子系统
41 | //相当于子系统A
42 | public class RegisterCourse
43 | {
44 | public bool CheckAvailable(string courseName)
45 | {
46 | Console.WriteLine("正在验证课程 {0}是否人数已满", courseName);
47 | return true;
48 | }
49 | }
50 |
51 | //相当于子系统B
52 | public class NotifyStudent
53 | {
54 | public bool Notify(string studentName)
55 | {
56 | Console.WriteLine("正在向{0}发生通知", studentName);
57 | return true;
58 | }
59 | }
60 | #endregion
61 | }
62 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/12享元模式/FlyweightPattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 |
7 | namespace CSharpDesignPatternDemo
8 | {
9 | public class FlyweightPattern
10 | {
11 | FlyweightPattern()
12 | {
13 | // 定义外部状态,例如字母的位置等信息
14 | int externalstate = 10;
15 | // 初始化享元工厂
16 | FlyweightFactory factory = new FlyweightFactory();
17 |
18 | // 判断是否已经创建了字母A,如果已经创建就直接使用创建的对象A
19 | Flyweight fa = factory.GetFlyweight("A");
20 | if (fa != null)
21 | {
22 | // 把外部状态作为享元对象的方法调用参数
23 | fa.Operation(--externalstate);
24 | }
25 | // 判断是否已经创建了字母B
26 | Flyweight fb = factory.GetFlyweight("B");
27 | if (fb != null)
28 | {
29 | fb.Operation(--externalstate);
30 | }
31 | // 判断是否已经创建了字母C
32 | Flyweight fc = factory.GetFlyweight("C");
33 | if (fc != null)
34 | {
35 | fc.Operation(--externalstate);
36 | }
37 | // 判断是否已经创建了字母D
38 | Flyweight fd = factory.GetFlyweight("D");
39 | if (fd != null)
40 | {
41 | fd.Operation(--externalstate);
42 | }
43 | else
44 | {
45 | Console.WriteLine("驻留池中不存在字符串D");
46 | // 这时候就需要创建一个对象并放入驻留池中
47 | ConcreteFlyweight d = new ConcreteFlyweight("D");
48 | factory.flyweights.Add("D", d);
49 | }
50 |
51 | Console.Read();
52 | }
53 | }
54 | //
55 | /// 享元工厂,负责创建和管理享元对象
56 | ///
57 | public class FlyweightFactory
58 | {
59 | public Hashtable flyweights = new Hashtable();
60 | public FlyweightFactory()
61 | {
62 | flyweights.Add("A", new ConcreteFlyweight("A"));
63 | flyweights.Add("B", new ConcreteFlyweight("B"));
64 | flyweights.Add("C", new ConcreteFlyweight("C"));
65 | }
66 |
67 | public Flyweight GetFlyweight(string key)
68 | {
69 | return flyweights[key] as Flyweight;
70 | }
71 | }
72 | ///
73 | /// 抽象享元类,提供具体享元类具有的方法
74 | ///
75 | public abstract class Flyweight
76 | {
77 | public abstract void Operation(int extrinsicstate);
78 | }
79 |
80 | // 具体的享元对象,这样我们不把每个字母设计成一个单独的类了,而是作为把共享的字母作为享元对象的内部状态
81 | public class ConcreteFlyweight:Flyweight
82 | {
83 | // 内部状态
84 | private string intrinsicstate;
85 | // 构造函数
86 | public ConcreteFlyweight(string innerState)
87 | {
88 | this.intrinsicstate = innerState;
89 | }
90 | ///
91 | /// 享元类的实例方法
92 | ///
93 | /// 外部状态
94 | public override void Operation(int extrinsicstate)
95 | {
96 | Console.WriteLine("具体实现类: intrinsicstate {0}, extrinsicstate {1}", intrinsicstate, extrinsicstate);
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/13代理模式/ProxyPattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpDesignPatternDemo
7 | {
8 | public class ProxyPattern
9 | {
10 | ProxyPattern()
11 | {
12 | // 创建一个代理对象并发出请求
13 | Person proxy = new Friend();
14 | proxy.BuyProduct();
15 | Console.Read();
16 | }
17 | }
18 |
19 | ///
20 | /// 抽象主题角色
21 | ///
22 | public abstract class Person
23 | {
24 | public abstract void BuyProduct();
25 | }
26 |
27 | ///
28 | /// 真实主题角色
29 | ///
30 | public class RealBuyPerson:Person
31 | {
32 | public override void BuyProduct()
33 | {
34 | Console.WriteLine("帮我买一个IPhone和一台苹果电脑");
35 | }
36 | }
37 |
38 | //代理角色
39 | public class Friend:Person
40 | {
41 | //引用真实主题实例
42 | RealBuyPerson realSubject;
43 | public override void BuyProduct()
44 | {
45 | Console.WriteLine("通过代理类访问真实实体对象的方法");
46 | if(realSubject==null)
47 | {
48 | realSubject = new RealBuyPerson();
49 | }
50 | this.PreBuyProduct();
51 | //调用真实主题方法
52 | realSubject.BuyProduct();
53 | this.PostBuyProduct();
54 | }
55 |
56 | // 代理角色执行的一些操作
57 | public void PreBuyProduct()
58 | {
59 | // 可能不知一个朋友叫这位朋友带东西,首先这位出国的朋友要对每一位朋友要带的东西列一个清单等
60 | Console.WriteLine("我怕弄糊涂了,需要列一张清单,张三:要带相机,李四:要带Iphone...........");
61 | }
62 |
63 | // 买完东西之后,代理角色需要针对每位朋友需要的对买来的东西进行分类
64 | public void PostBuyProduct()
65 | {
66 | Console.WriteLine("终于买完了,现在要对东西分一下,相机是张三的;Iphone是李四的..........");
67 | }
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/14模板方法/TemplateMethod.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpDesignPatternDemo
7 | {
8 | public class TemplateMethod
9 | {
10 | TemplateMethod()
11 | {
12 | // 创建一个菠菜实例并调用模板方法
13 | Spinach spinach = new Spinach();
14 | spinach.CookVegetabel();
15 | Console.Read();
16 | }
17 | }
18 |
19 | public abstract class Vegetabel
20 | {
21 | // 模板方法,不要把模版方法定义为Virtual或abstract方法,避免被子类重写,防止更改流程的执行顺序
22 | public void CookVegetabel()
23 | {
24 | Console.WriteLine("抄蔬菜的一般做法");
25 | this.pourOil();
26 | this.HeatOil();
27 | this.pourVegetabel();
28 | this.stir_fry();
29 | }
30 | // 第一步倒油
31 | public void pourOil()
32 | {
33 | Console.WriteLine("倒油");
34 | }
35 |
36 | // 把油烧热
37 | public void HeatOil()
38 | {
39 | Console.WriteLine("把油烧热");
40 | }
41 |
42 | // 油热了之后倒蔬菜下去,具体哪种蔬菜由子类决定
43 | public abstract void pourVegetabel();
44 |
45 | // 开发翻炒蔬菜
46 | public void stir_fry()
47 | {
48 | Console.WriteLine("翻炒");
49 | }
50 | }
51 |
52 | // 菠菜
53 | public class Spinach : Vegetabel
54 | {
55 |
56 | public override void pourVegetabel()
57 | {
58 | Console.WriteLine("倒菠菜进锅中");
59 | }
60 | }
61 |
62 | // 大白菜
63 | public class ChineseCabbage : Vegetabel
64 | {
65 | public override void pourVegetabel()
66 | {
67 | Console.WriteLine("倒大白菜进锅中");
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/15命令模式/CommandPattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpDesignPatternDemo
7 | {
8 | public class CommandPattern
9 | {
10 | CommandPattern()
11 | {
12 | // 初始化Receiver、Invoke和Command
13 | Receiver r = new Receiver();
14 | Command c = new ConcreteCommand(r);
15 | Invoke i = new Invoke(c);
16 |
17 | // 院领导发出命令
18 | i.ExecuteCommand();
19 | }
20 | }
21 | // 教官,负责调用命令对象执行请求
22 | public class Invoke
23 | {
24 | public Command _command;
25 | public Invoke(Command command)
26 | {
27 | this._command = command;
28 | }
29 |
30 | public void ExecuteCommand()
31 | {
32 | _command.Action();
33 | }
34 | }
35 | // 命令抽象类
36 | public abstract class Command
37 | {
38 | // 命令应该知道接收者是谁,所以有Receiver这个成员变量
39 | protected Receiver _receiver;
40 | public Command(Receiver receiver)
41 | {
42 | this._receiver = receiver;
43 | }
44 |
45 | //命令执行方法
46 | public abstract void Action();
47 | }
48 | public class ConcreteCommand : Command
49 | {
50 | public ConcreteCommand(Receiver receiver) : base(receiver)
51 | {
52 |
53 | }
54 | public override void Action()
55 | {
56 | // 调用接收的方法,因为执行命令的是学生
57 | _receiver.Run1000Meters();
58 | }
59 | }
60 |
61 | // 命令接收者——学生
62 | public class Receiver
63 | {
64 | public void Run1000Meters()
65 | {
66 | Console.WriteLine("跑1000米");
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/16迭代器模式/IteratorPattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpDesignPatternDemo
7 | {
8 | public class IteratorPattern
9 | {
10 | IteratorPattern()
11 | {
12 | Iterator iterator;
13 | IListCollection list = new ConcreteList();
14 | iterator = list.GetIterator();
15 |
16 | while (iterator.MoveNext())
17 | {
18 | int i = (int)iterator.GetCurrent();
19 | Console.WriteLine(i.ToString());
20 | iterator.Next();
21 | }
22 |
23 | Console.Read();
24 | }
25 | }
26 | // 抽象聚合类
27 | public interface IListCollection
28 | {
29 | Iterator GetIterator();
30 | }
31 |
32 | // 迭代器抽象类
33 | public interface Iterator
34 | {
35 | bool MoveNext();
36 | object GetCurrent();
37 | void Next();
38 | void Reset();
39 | }
40 |
41 | // 具体聚合类
42 | public class ConcreteList : IListCollection
43 | {
44 | int[] collection;
45 | public ConcreteList()
46 | {
47 | collection = new int[] { 2, 4, 6, 8 };
48 | }
49 |
50 | public Iterator GetIterator()
51 | {
52 | return new ConcreteIterator(this);
53 | }
54 |
55 | public int Length
56 | {
57 | get { return collection.Length; }
58 | }
59 |
60 | public int GetElement(int index)
61 | {
62 | return collection[index];
63 | }
64 |
65 | }
66 |
67 | // 具体迭代器类
68 | public class ConcreteIterator : Iterator
69 | {
70 | // 迭代器要集合对象进行遍历操作,自然就需要引用集合对象
71 | private ConcreteList _list;
72 | private int _index;
73 |
74 | public ConcreteIterator(ConcreteList list)
75 | {
76 | _list = list;
77 | _index = 0;
78 | }
79 |
80 |
81 | public bool MoveNext()
82 | {
83 | if (_index < _list.Length)
84 | {
85 | return true;
86 | }
87 | return false;
88 | }
89 |
90 | public Object GetCurrent()
91 | {
92 | return _list.GetElement(_index);
93 | }
94 |
95 | public void Reset()
96 | {
97 | _index = 0;
98 | }
99 |
100 | public void Next()
101 | {
102 | if (_index < _list.Length)
103 | {
104 | _index++;
105 | }
106 |
107 | }
108 | }
109 |
110 | }
111 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/17观察者模式/ObserverPattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpDesignPatternDemo
7 | {
8 | public class ObserverPattern
9 | {
10 | ObserverPattern()
11 | {
12 | TenXun tenXun = new TenXunGame("TenXun Game", "Have a new game published ....");
13 |
14 | // 添加订阅者
15 | tenXun.AddObserver(new Subscriber("Learning Hard"));
16 | tenXun.AddObserver(new Subscriber("Tom"));
17 |
18 | tenXun.Update();
19 |
20 | Console.ReadLine();
21 | }
22 | }
23 | // 订阅号抽象类
24 | public abstract class TenXun
25 | {
26 | // 保存订阅者列表
27 | private List observers = new List();
28 |
29 | public string Symbol { get; set; }
30 | public string Info { get; set; }
31 | public TenXun(string symbol, string info)
32 | {
33 | this.Symbol = symbol;
34 | this.Info = info;
35 | }
36 |
37 | #region 新增对订阅号列表的维护操作
38 | public void AddObserver(IObserver ob)
39 | {
40 | observers.Add(ob);
41 | }
42 | public void RemoveObserver(IObserver ob)
43 | {
44 | observers.Remove(ob);
45 | }
46 | #endregion
47 |
48 | public void Update()
49 | {
50 | // 遍历订阅者列表进行通知
51 | foreach (IObserver ob in observers)
52 | {
53 | if (ob != null)
54 | {
55 | ob.ReceiveAndPrint(this);
56 | }
57 | }
58 | }
59 | }
60 |
61 | // 具体订阅号类
62 | public class TenXunGame : TenXun
63 | {
64 | public TenXunGame(string symbol, string info)
65 | : base(symbol, info)
66 | {
67 | }
68 | }
69 |
70 | // 订阅者接口
71 | public interface IObserver
72 | {
73 | void ReceiveAndPrint(TenXun tenxun);
74 | }
75 |
76 | // 具体的订阅者类
77 | public class Subscriber : IObserver
78 | {
79 | public string Name { get; set; }
80 | public Subscriber(string name)
81 | {
82 | this.Name = name;
83 | }
84 |
85 | public void ReceiveAndPrint(TenXun tenxun)
86 | {
87 | Console.WriteLine("Notified {0} of {1}'s" + " Info is: {2}", Name, tenxun.Symbol, tenxun.Info);
88 | }
89 | }
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/18中介者模式/MediatorPattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpDesignPatternDemo
7 | {
8 | public class MediatorPattern
9 | {
10 | MediatorPattern()
11 | {
12 | AbstractCardPartner A = new ParterA();
13 | AbstractCardPartner B = new ParterB();
14 | // 初始钱
15 | A.MoneyCount = 20;
16 | B.MoneyCount = 20;
17 |
18 | AbstractMediator mediator = new MediatorPater(A, B);
19 |
20 | // A赢了
21 | A.ChangeCount(5, mediator);
22 | Console.WriteLine("A 现在的钱是:{0}", A.MoneyCount);// 应该是25
23 | Console.WriteLine("B 现在的钱是:{0}", B.MoneyCount); // 应该是15
24 |
25 | // B 赢了
26 | B.ChangeCount(10, mediator);
27 | Console.WriteLine("A 现在的钱是:{0}", A.MoneyCount);// 应该是15
28 | Console.WriteLine("B 现在的钱是:{0}", B.MoneyCount); // 应该是25
29 | Console.Read();
30 | }
31 | }
32 | // 抽象牌友类
33 | public abstract class AbstractCardPartner
34 | {
35 | public int MoneyCount { get; set; }
36 | public AbstractCardPartner()
37 | {
38 | MoneyCount = 0;
39 | }
40 | public abstract void ChangeCount(int Count, AbstractMediator mediator);
41 | }
42 | // 牌友A类
43 | public class ParterA : AbstractCardPartner
44 | {
45 | // 依赖与抽象中介者对象
46 | public override void ChangeCount(int Count, AbstractMediator mediator)
47 | {
48 | mediator.AWin(Count);
49 | }
50 | }
51 | // 牌友B类
52 | public class ParterB : AbstractCardPartner
53 | {
54 | // 依赖与抽象中介者对象
55 | public override void ChangeCount(int Count, AbstractMediator mediator)
56 | {
57 | mediator.BWin(Count);
58 | }
59 | }
60 | // 抽象中介者类
61 | public abstract class AbstractMediator
62 | {
63 | protected AbstractCardPartner A;
64 | protected AbstractCardPartner B;
65 | public AbstractMediator(AbstractCardPartner a, AbstractCardPartner b)
66 | {
67 | A = a;
68 | B = b;
69 | }
70 | public abstract void AWin(int count);
71 | public abstract void BWin(int count);
72 | }
73 | // 具体中介者类
74 | public class MediatorPater : AbstractMediator
75 | {
76 | public MediatorPater(AbstractCardPartner a, AbstractCardPartner b) : base(a, b)
77 | { }
78 | public override void AWin(int count)
79 | {
80 | A.MoneyCount += count;
81 | B.MoneyCount -= count;
82 | }
83 |
84 | public override void BWin(int count)
85 | {
86 | B.MoneyCount += count;
87 | A.MoneyCount -= count;
88 | }
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/19状态者模式/StatePattern.cs:
--------------------------------------------------------------------------------
1 |
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 |
7 | namespace CSharpDesignPatternDemo
8 | {
9 | public class StatePattern
10 | {
11 | StatePattern()
12 | {
13 | // 开一个新的账户
14 | Account account = new Account("Learning Hard");
15 |
16 | // 进行交易
17 | // 存钱
18 | account.Deposit(1000.0);
19 | account.Deposit(200.0);
20 | account.Deposit(600.0);
21 |
22 | // 付利息
23 | account.PayInterest();
24 |
25 | // 取钱
26 | account.Withdraw(2000.00);
27 | account.Withdraw(500.00);
28 |
29 | // 等待用户输入
30 | Console.ReadKey();
31 | }
32 | }
33 |
34 | public class Account
35 | {
36 | public State State { get; set; }
37 | public string Owner { get; set; }
38 | public Account(string owner)
39 | {
40 | this.Owner = owner;
41 | this.State = new SliverState(0.0, this);
42 |
43 | }
44 |
45 | public double Balance { get { return State.Balance; } }//余额
46 | //存钱
47 | public void Deposit(double amount)
48 | {
49 | State.Deposit(amount);
50 | Console.WriteLine("存款金额为 {0:C}——", amount);
51 | Console.WriteLine("账户余额为 =:{0:C}", this.Balance);
52 | Console.WriteLine("账户状态为: {0}", this.State.GetType().Name);
53 | Console.WriteLine();
54 | }
55 | //取钱
56 | public void Withdraw(double amount)
57 | {
58 | State.Withdraw(amount);
59 | Console.WriteLine("账户余额为 =:{0:C}", this.Balance);
60 | Console.WriteLine("账户状态为: {0}", this.State.GetType().Name);
61 | Console.WriteLine();
62 | }
63 |
64 | // 获得利息
65 | public void PayInterest()
66 | {
67 | State.PayInterest();
68 | Console.WriteLine("Interest Paid --- ");
69 | Console.WriteLine("账户余额为 =:{0:C}", this.Balance);
70 | Console.WriteLine("账户状态为: {0}", this.State.GetType().Name);
71 | Console.WriteLine();
72 | }
73 | }
74 |
75 | public abstract class State
76 | {
77 | public Account Account { get; set; }
78 | public double Balance { get; set; }//余额
79 | public double Interest { get; set; }//利率
80 | public double LowerLimit { get; set; }//下限
81 | public double UpperLimit { get; set; }//上限
82 | public abstract void Deposit(double amount);//存款
83 | public abstract void Withdraw(double amount);//取钱
84 | public abstract void PayInterest();//获得的利息
85 | }
86 |
87 | public class RedState:State
88 | {
89 | public RedState(State state)
90 | {
91 | this.Balance = state.Balance;
92 | this.Account = state.Account;
93 | Interest = 0.00;
94 | LowerLimit = -100.00;
95 | UpperLimit = 0.00;
96 | }
97 | //存钱
98 | public override void Deposit(double amount)
99 | {
100 | Balance += amount;
101 | StateChangeCheck();
102 | }
103 | //取钱
104 | public override void Withdraw(double amount)
105 | {
106 | Console.WriteLine("没有钱可以取了!");
107 | }
108 |
109 | public override void PayInterest()
110 | {
111 | //没有利息
112 | }
113 | private void StateChangeCheck()
114 | {
115 | if(Balance>UpperLimit)
116 | {
117 | Account.State = new SliverState(this);
118 | }
119 | }
120 | }
121 |
122 | public class SliverState:State
123 | {
124 | public SliverState(State state):this(state.Balance,state.Account)
125 | {
126 |
127 | }
128 |
129 | public SliverState(double balance,Account account)
130 | {
131 | this.Balance = balance;
132 | this.Account = account;
133 | Interest = 0.00;
134 | LowerLimit = 0.00;
135 | UpperLimit = 1000.00;
136 | }
137 |
138 | public override void Deposit(double amount)
139 | {
140 | Balance += amount;
141 | StateChangeCheck();
142 | }
143 |
144 | public override void Withdraw(double amount)
145 | {
146 | Balance -= amount;
147 | StateChangeCheck();
148 | }
149 |
150 | public override void PayInterest()
151 | {
152 | Balance += Interest * Balance;
153 | StateChangeCheck();
154 | }
155 | private void StateChangeCheck()
156 | {
157 | if(BalanceUpperLimit)
162 | {
163 | Account.State = new GoldState(this);
164 | }
165 | }
166 | }
167 |
168 | public class GoldState:State
169 | {
170 | public GoldState(State state)
171 | {
172 | this.Balance = state.Balance;
173 | this.Account = state.Account;
174 | Interest = 0.05;
175 | LowerLimit = 1000.00;
176 | UpperLimit = 1000000.00;
177 | }
178 |
179 | public override void Deposit(double amount)
180 | {
181 | Balance+=amount;
182 | StateChangeCheck();
183 | }
184 |
185 | public override void Withdraw(double amount)
186 | {
187 | Balance -= amount;
188 | StateChangeCheck();
189 | }
190 |
191 | public override void PayInterest()
192 | {
193 | Balance += Interest * Balance;
194 | StateChangeCheck();
195 | }
196 |
197 | private void StateChangeCheck()
198 | {
199 | if(Balance<0.0)
200 | {
201 | Account.State = new RedState(this);
202 | }
203 | else if(Balance 0 ? (income - 3500) * 0.45 : 0.0;
40 | }
41 | }
42 |
43 | public class InterestOperation
44 | {
45 | private ITaxStrategy m_strategy;
46 | public InterestOperation(ITaxStrategy strategy)
47 | {
48 | this.m_strategy = strategy;
49 | }
50 | public double GetTax(double income)
51 | {
52 | return m_strategy.CalculateTax(income);
53 | }
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/21责任链模式/ChainofResponsibility.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CSharpDesignPatternDemo
7 | {
8 | public class ChainofResponsibility
9 | {
10 | public ChainofResponsibility()
11 | {
12 | PurchaseRequest requestTelphone = new PurchaseRequest(4000.0, "Telphone");
13 | PurchaseRequest requestSoftware = new PurchaseRequest(10000.0, "Visual Studio");
14 | PurchaseRequest requestComputers = new PurchaseRequest(40000.0, "Computers");
15 |
16 | Approver manager = new Manager("LearningHard");
17 | Approver Vp = new VicePresident("Tony");
18 | Approver Pre = new President("BossTom");
19 |
20 | // 设置责任链
21 | manager.NextApprover = Vp;
22 | Vp.NextApprover = Pre;
23 |
24 | // 处理请求
25 | manager.ProcessRequest(requestTelphone);
26 | manager.ProcessRequest(requestSoftware);
27 | manager.ProcessRequest(requestComputers);
28 | Console.ReadLine();
29 | }
30 | }
31 | // 采购请求
32 | public class PurchaseRequest
33 | {
34 | // 金额
35 | public double Amount { get; set; }
36 | // 产品名字
37 | public string ProductName { get; set; }
38 | public PurchaseRequest(double amount, string productName)
39 | {
40 | Amount = amount;
41 | ProductName = productName;
42 | }
43 | }
44 | // 审批人,Handler
45 | public abstract class Approver
46 | {
47 | public Approver NextApprover { get; set; }
48 | public string Name { get; set; }
49 | public Approver(string name)
50 | {
51 | Name = name;
52 | }
53 |
54 | public abstract void ProcessRequest(PurchaseRequest request);
55 | }
56 | // ConcreteHandler
57 | public class Manager : Approver
58 | {
59 | public Manager(string name) : base(name)
60 | { }
61 |
62 | public override void ProcessRequest(PurchaseRequest request)
63 | {
64 | if (request.Amount < 1000.00)
65 | {
66 | Console.WriteLine("{0}-{1} approved the request of purshing {2}", this, Name, request.ProductName);
67 | }
68 | else if (NextApprover != null)
69 | {
70 | NextApprover.ProcessRequest(request);
71 | }
72 | }
73 | }
74 | // ConcreteHandler,副总
75 | public class VicePresident : Approver
76 | {
77 | public VicePresident(string name) : base(name)
78 | {
79 |
80 | }
81 | public override void ProcessRequest(PurchaseRequest request)
82 | {
83 | if (request.Amount < 25000.00)
84 | {
85 | Console.WriteLine("{0}-{1} approved the request of purshing {2}", this, Name, request.ProductName);
86 | }
87 | else if (NextApprover != null)
88 | {
89 | NextApprover.ProcessRequest(request);
90 | }
91 | }
92 | }
93 | // ConcreteHandler,副总
94 | public class President : Approver
95 | {
96 | public President(string name) : base(name)
97 | { }
98 | public override void ProcessRequest(PurchaseRequest request)
99 | {
100 | if (request.Amount < 100000.00)
101 | {
102 | Console.WriteLine("{0}-{1} approved the request of purshing {2}", this, Name, request.ProductName);
103 | }
104 | else
105 | {
106 | Console.WriteLine("Request需要组织一个会议讨论");
107 | }
108 | }
109 | }
110 |
111 |
112 | }
113 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/22访问者模式/VistorPattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 |
7 | namespace CSharpDesignPatternDemo
8 | {
9 | public class VistorPattern
10 | {
11 | public VistorPattern()
12 | {
13 | ObjectStructure objectStructure = new ObjectStructure();
14 | foreach (Element e in objectStructure.Elements)
15 | {
16 | // 每个元素接受访问者访问
17 | e.Accept(new ConcreteVistor());
18 | }
19 |
20 | Console.Read();
21 | }
22 | }
23 | // 抽象元素角色
24 | public abstract class Element
25 | {
26 | public abstract void Accept(IVistor vistor);
27 | public abstract void Print();
28 | }
29 |
30 | // 具体元素A
31 | public class ElementA : Element
32 | {
33 | public override void Accept(IVistor vistor)
34 | {
35 | // 调用访问者visit方法
36 | vistor.Visit(this);
37 | }
38 | public override void Print()
39 | {
40 | Console.WriteLine("我是元素A");
41 | }
42 | }
43 |
44 | // 具体元素B
45 | public class ElementB : Element
46 | {
47 | public override void Accept(IVistor vistor)
48 | {
49 | vistor.Visit(this);
50 | }
51 | public override void Print()
52 | {
53 | Console.WriteLine("我是元素B");
54 | }
55 | }
56 |
57 | // 抽象访问者
58 | public interface IVistor
59 | {
60 | void Visit(ElementA a);
61 | void Visit(ElementB b);
62 | }
63 |
64 | // 具体访问者
65 | public class ConcreteVistor : IVistor
66 | {
67 | // visit方法而是再去调用元素的Accept方法
68 | public void Visit(ElementA a)
69 | {
70 | a.Print();
71 | }
72 | public void Visit(ElementB b)
73 | {
74 | b.Print();
75 | }
76 | }
77 |
78 | // 对象结构
79 | public class ObjectStructure
80 | {
81 | private ArrayList elements = new ArrayList();
82 |
83 | public ArrayList Elements
84 | {
85 | get { return elements; }
86 | }
87 |
88 | public ObjectStructure()
89 | {
90 | Random ran = new Random();
91 | for (int i = 0; i < 6; i++)
92 | {
93 | int ranNum = ran.Next(10);
94 | if (ranNum > 5)
95 | {
96 | elements.Add(new ElementA());
97 | }
98 | else
99 | {
100 | elements.Add(new ElementB());
101 | }
102 | }
103 | }
104 | }
105 |
106 | }
107 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/23备忘录模式/MementoPattern.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading;
6 |
7 | namespace CSharpDesignPatternDemo
8 | {
9 | public class MementoPattern
10 | {
11 | MementoPattern()
12 | {
13 | List persons = new List()
14 | {
15 | new ContactPerson() { Name= "Learning Hard", MobileNum = "123445"},
16 | new ContactPerson() { Name = "Tony", MobileNum = "234565"},
17 | new ContactPerson() { Name = "Jock", MobileNum = "231455"}
18 | };
19 |
20 | MobileOwner mobileOwner = new MobileOwner(persons);
21 | mobileOwner.Show();
22 |
23 | // 创建备忘录并保存备忘录对象
24 | Caretaker caretaker = new Caretaker();
25 | caretaker.ContactMementoDic.Add(DateTime.Now.ToString(), mobileOwner.CreateMemento());
26 |
27 | // 更改发起人联系人列表
28 | Console.WriteLine("----移除最后一个联系人--------");
29 | mobileOwner.ContactPersons.RemoveAt(2);
30 | mobileOwner.Show();
31 |
32 | // 创建第二个备份
33 | Thread.Sleep(1000);
34 | caretaker.ContactMementoDic.Add(DateTime.Now.ToString(), mobileOwner.CreateMemento());
35 |
36 | // 恢复到原始状态
37 | Console.WriteLine("-------恢复联系人列表,请从以下列表选择恢复的日期------");
38 | var keyCollection = caretaker.ContactMementoDic.Keys;
39 | foreach (string k in keyCollection)
40 | {
41 | Console.WriteLine("Key = {0}", k);
42 | }
43 | while (true)
44 | {
45 | Console.Write("请输入数字,按窗口的关闭键退出:");
46 |
47 | int index = -1;
48 | try
49 | {
50 | index = Int32.Parse(Console.ReadLine());
51 | }
52 | catch
53 | {
54 | Console.WriteLine("输入的格式错误");
55 | continue;
56 | }
57 |
58 | ContactMemento contactMentor = null;
59 | if (index < keyCollection.Count && caretaker.ContactMementoDic.TryGetValue(keyCollection.ElementAt(index), out contactMentor))
60 | {
61 | mobileOwner.RestoreMemento(contactMentor);
62 | mobileOwner.Show();
63 | }
64 | else
65 | {
66 | Console.WriteLine("输入的索引大于集合长度!");
67 | }
68 | }
69 | }
70 | }
71 |
72 | // 联系人
73 | public class ContactPerson
74 | {
75 | public string Name { get; set; }
76 | public string MobileNum { get; set; }
77 | }
78 |
79 | // 发起人
80 | public class MobileOwner
81 | {
82 | public List ContactPersons { get; set; }
83 | public MobileOwner(List persons)
84 | {
85 | ContactPersons = persons;
86 | }
87 |
88 | // 创建备忘录,将当期要保存的联系人列表导入到备忘录中
89 | public ContactMemento CreateMemento()
90 | {
91 | // 这里也应该传递深拷贝,new List方式传递的是浅拷贝,
92 | // 因为ContactPerson类中都是string类型,所以这里new list方式对ContactPerson对象执行了深拷贝
93 | // 如果ContactPerson包括非string的引用类型就会有问题,所以这里也应该用序列化传递深拷贝
94 | return new ContactMemento(new List(this.ContactPersons));
95 | }
96 |
97 | // 将备忘录中的数据备份导入到联系人列表中
98 | public void RestoreMemento(ContactMemento memento)
99 | {
100 | if (memento != null)
101 | {
102 | // 下面这种方式是错误的,因为这样传递的是引用,
103 | // 则删除一次可以恢复,但恢复之后再删除的话就恢复不了.
104 | // 所以应该传递contactPersonBack的深拷贝,深拷贝可以使用序列化来完成
105 | this.ContactPersons = memento.ContactPersonBack;
106 | }
107 | }
108 | public void Show()
109 | {
110 | Console.WriteLine("联系人列表中有{0}个人,他们是:", ContactPersons.Count);
111 | foreach (ContactPerson p in ContactPersons)
112 | {
113 | Console.WriteLine("姓名: {0} 号码为: {1}", p.Name, p.MobileNum);
114 | }
115 | }
116 | }
117 |
118 | // 备忘录
119 | public class ContactMemento
120 | {
121 | public List ContactPersonBack { get; set; }
122 | public ContactMemento(List persons)
123 | {
124 | ContactPersonBack = persons;
125 | }
126 | }
127 |
128 | // 管理角色
129 | public class Caretaker
130 | {
131 | // 使用多个备忘录来存储多个备份点
132 | public Dictionary ContactMementoDic { get; set; }
133 | public Caretaker()
134 | {
135 | ContactMementoDic = new Dictionary();
136 | }
137 | }
138 |
139 |
140 | }
141 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/App.xaml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Configuration;
4 | using System.Data;
5 | using System.Linq;
6 | using System.Windows;
7 |
8 | namespace CSharpDesignPatternDemo
9 | {
10 | ///
11 | /// App.xaml 的交互逻辑
12 | ///
13 | public partial class App : Application
14 | {
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/CSharpDesignPatternDemo.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {AA113DB3-4117-4526-9197-11E33209CBFB}
8 | WinExe
9 | Properties
10 | CSharpDesignPatternDemo
11 | CSharpDesignPatternDemo
12 | v4.0
13 | 512
14 | {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
15 | 4
16 |
17 |
18 | AnyCPU
19 | true
20 | full
21 | false
22 | bin\Debug\
23 | DEBUG;TRACE
24 | prompt
25 | 4
26 |
27 |
28 | AnyCPU
29 | pdbonly
30 | true
31 | bin\Release\
32 | TRACE
33 | prompt
34 | 4
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 | 4.0
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 | MSBuild:Compile
54 | Designer
55 |
56 |
57 |
58 |
59 |
60 | Singleton.xaml
61 |
62 |
63 | MSBuild:Compile
64 | Designer
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 | App.xaml
89 | Code
90 |
91 |
92 | MainWindow.xaml
93 | Code
94 |
95 |
96 | Designer
97 | MSBuild:Compile
98 |
99 |
100 |
101 |
102 | Code
103 |
104 |
105 | True
106 | True
107 | Resources.resx
108 |
109 |
110 | True
111 | Settings.settings
112 | True
113 |
114 |
115 | ResXFileCodeGenerator
116 | Resources.Designer.cs
117 |
118 |
119 | SettingsSingleFileGenerator
120 | Settings.Designer.cs
121 |
122 |
123 |
124 |
125 |
126 |
133 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/MainWindow.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/MainWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Windows;
6 | using System.Windows.Controls;
7 | using System.Windows.Data;
8 | using System.Windows.Documents;
9 | using System.Windows.Input;
10 | using System.Windows.Media;
11 | using System.Windows.Media.Imaging;
12 | using System.Windows.Navigation;
13 | using System.Windows.Shapes;
14 |
15 | namespace CSharpDesignPatternDemo
16 | {
17 | ///
18 | /// MainWindow.xaml 的交互逻辑
19 | ///
20 | public partial class MainWindow : Window
21 | {
22 | public MainWindow()
23 | {
24 | InitializeComponent();
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Resources;
3 | using System.Runtime.CompilerServices;
4 | using System.Runtime.InteropServices;
5 | using System.Windows;
6 |
7 | // 有关程序集的一般信息由以下
8 | // 控制。更改这些特性值可修改
9 | // 与程序集关联的信息。
10 | [assembly: AssemblyTitle("CSharpDesignPatternDemo")]
11 | [assembly: AssemblyDescription("")]
12 | [assembly: AssemblyConfiguration("")]
13 | [assembly: AssemblyCompany("")]
14 | [assembly: AssemblyProduct("CSharpDesignPatternDemo")]
15 | [assembly: AssemblyCopyright("Copyright © 2017")]
16 | [assembly: AssemblyTrademark("")]
17 | [assembly: AssemblyCulture("")]
18 |
19 | //将 ComVisible 设置为 false 将使此程序集中的类型
20 | //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
21 | //请将此类型的 ComVisible 特性设置为 true。
22 | [assembly: ComVisible(false)]
23 |
24 | //若要开始生成可本地化的应用程序,请
25 | // 中的 .csproj 文件中
26 | //例如,如果您在源文件中使用的是美国英语,
27 | //使用的是美国英语,请将 设置为 en-US。 然后取消
28 | //对以下 NeutralResourceLanguage 特性的注释。 更新
29 | //以下行中的“en-US”以匹配项目文件中的 UICulture 设置。
30 |
31 | //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
32 |
33 |
34 | [assembly: ThemeInfo(
35 | ResourceDictionaryLocation.None, //主题特定资源词典所处位置
36 | //(当资源未在页面
37 | //或应用程序资源字典中找到时使用)
38 | ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
39 | //(当资源未在页面
40 | //、应用程序或任何主题专用资源字典中找到时使用)
41 | )]
42 |
43 |
44 | // 程序集的版本信息由下列四个值组成:
45 | //
46 | // 主版本
47 | // 次版本
48 | // 生成号
49 | // 修订号
50 | //
51 | //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
52 | // 方法是按如下所示使用“*”: :
53 | // [assembly: AssemblyVersion("1.0.*")]
54 | [assembly: AssemblyVersion("1.0.0.0")]
55 | [assembly: AssemblyFileVersion("1.0.0.0")]
56 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本: 4.0.30319.42000
5 | //
6 | // 对此文件的更改可能导致不正确的行为,如果
7 | // 重新生成代码,则所做更改将丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace CSharpDesignPatternDemo.Properties
12 | {
13 |
14 |
15 | ///
16 | /// 强类型资源类,用于查找本地化字符串等。
17 | ///
18 | // 此类是由 StronglyTypedResourceBuilder
19 | // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
20 | // 若要添加或删除成员,请编辑 .ResX 文件,然后重新运行 ResGen
21 | // (以 /str 作为命令选项),或重新生成 VS 项目。
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources
26 | {
27 |
28 | private static global::System.Resources.ResourceManager resourceMan;
29 |
30 | private static global::System.Globalization.CultureInfo resourceCulture;
31 |
32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
33 | internal Resources()
34 | {
35 | }
36 |
37 | ///
38 | /// 返回此类使用的缓存 ResourceManager 实例。
39 | ///
40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
41 | internal static global::System.Resources.ResourceManager ResourceManager
42 | {
43 | get
44 | {
45 | if ((resourceMan == null))
46 | {
47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CSharpDesignPatternDemo.Properties.Resources", typeof(Resources).Assembly);
48 | resourceMan = temp;
49 | }
50 | return resourceMan;
51 | }
52 | }
53 |
54 | ///
55 | /// 覆盖当前线程的 CurrentUICulture 属性
56 | /// 使用此强类型的资源类的资源查找。
57 | ///
58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
59 | internal static global::System.Globalization.CultureInfo Culture
60 | {
61 | get
62 | {
63 | return resourceCulture;
64 | }
65 | set
66 | {
67 | resourceCulture = value;
68 | }
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | text/microsoft-resx
107 |
108 |
109 | 2.0
110 |
111 |
112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
113 |
114 |
115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace CSharpDesignPatternDemo.Properties
12 | {
13 |
14 |
15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
18 | {
19 |
20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
21 |
22 | public static Settings Default
23 | {
24 | get
25 | {
26 | return defaultInstance;
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/bin/Debug/CSharpDesignPatternDemo.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/caomfan/CSharpDesignPatternDemo/fda58651b387336259b5d3a1c86de839c8ecf3f7/CSharpDesignPatternDemo/CSharpDesignPatternDemo/bin/Debug/CSharpDesignPatternDemo.exe
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/bin/Debug/CSharpDesignPatternDemo.pdb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/caomfan/CSharpDesignPatternDemo/fda58651b387336259b5d3a1c86de839c8ecf3f7/CSharpDesignPatternDemo/CSharpDesignPatternDemo/bin/Debug/CSharpDesignPatternDemo.pdb
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/bin/Debug/CSharpDesignPatternDemo.vshost.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/caomfan/CSharpDesignPatternDemo/fda58651b387336259b5d3a1c86de839c8ecf3f7/CSharpDesignPatternDemo/CSharpDesignPatternDemo/bin/Debug/CSharpDesignPatternDemo.vshost.exe
--------------------------------------------------------------------------------
/CSharpDesignPatternDemo/CSharpDesignPatternDemo/bin/Debug/CSharpDesignPatternDemo.vshost.exe.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # c# 设计模式大全
2 |
--------------------------------------------------------------------------------
/项目说明.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/caomfan/CSharpDesignPatternDemo/fda58651b387336259b5d3a1c86de839c8ecf3f7/项目说明.txt
--------------------------------------------------------------------------------