设计模式
口诀
创建型模式:工建单原
结构型模式:适享代组装外桥
行为型模式:命中观测解责备,迭状模访
六大原则:单开里接依迪
# 设计模式
设计模式三大类型:
创建型设计模式:关注对象的创建
结构型设计模式:关注类与类之间的关系
纵向关系:继承≈实现 超强关联
横向关系:组合>聚合>关联>依赖
行为型设计模式:关注对象和行为的分离
# 创建型设计模式
# 1、单例模式
就是限制对象的创建,重用了对象
//单例模式的三种方式
/// 一
// ***********************************************************************************
/// <summary>
/// 懒汉式
/// </summary>
public class Singleton
{
/// <summary>
/// 构造函数私有化,避免别人还去new
/// 公开的静态方法提供对象实例
/// 初始化一个静态字段用于返回,保证全局都是这一个
/// </summary>
private Singleton()
{
Console.WriteLine($"{this.GetType().Name}被构造一次");
}
private static volatile Singleton _singleton = null; //volatile 促进线程安全 让线程按顺序操作
private static readonly object Singleton_Lock = new object();
public static Singleton CreateSingleton()
{
if (_singleton == null) //是——singleton已经被初始之后,就不要进入锁等待了
{
lock (Singleton_Lock) //保证任意时刻只有一个线程进入lock线程,也限制了并发
{
if (_singleton == null) //保证只实例化一次
{
_singleton = new Singleton();
}
}
}
return _singleton;
}
public int iTotal = 0;
public void Show()
{
lock (Singleton_Lock) //保证多线程调用时得到正确的结果
{
this.iTotal++;
}
}
}
/// 二
// ***********************************************************************************
/// <summary>
/// 饿汉式
/// </summary>
public class SingletonSecond
{
/// <summary>
/// 1、构造函数耗时耗资源
/// </summary>
private SingletonSecond()
{
Console.WriteLine($"{this.GetType().Name}被构造一次");
}
/// <summary>
/// 静态构造函数:由CLR保证,程序第一次使用这个类型前被调用,且只调用一次
///
/// 做一些检测、初始化的动作
/// 写日志功能的文件夹检测
/// XML配置文件
/// </summary>
static SingletonSecond()
{
_singletonSecond=new SingletonSecond();
Console.WriteLine($"SingletonSecond 被启动");
}
private static SingletonSecond _singletonSecond = null;
public static SingletonSecond CreateInstance()
{
return _singletonSecond;
}
public static void Test()
{
Console.WriteLine("Test2");
}
public int iTotal = 0;
public void Show()
{
this.iTotal++;
}
}
/// 三
// ***********************************************************************************
public class SingletonThird
{
private SingletonThird()
{
Console.WriteLine($"{this.GetType().Name} 被构造一次");
}
/// <summary>
/// 静态字段:在第一次使用这个类之前,由CLR保证,初始化且只初始化一次
/// 这个比静态构造函数还早
/// </summary>
private static SingletonThird _singletonThird=new SingletonThird();
public static SingletonThird CreateInstance()
{
return _singletonThird;
}
public void Show()
{
Console.WriteLine($"这里是{this.GetType().Name}.Show ");
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
107
# 2、原型模式
换个方式创建对象,不走构造函数,而是内存拷贝
/// <summary>
/// 原型模式:在单例的基础上升级了一下,把对象从内存层面克隆了一下,然后返回
/// 既是一个新对象,但是又不是new出来的
/// </summary>
public class Prototype
{
private Prototype()
{
long lResult = 0;
for (int i = 0; i < 10000; i++)
{
lResult += 1;
}
Thread.Sleep(1000);
Console.WriteLine($"{this.GetType().Name} 被构造一次");
}
private static Prototype _prototype = new Prototype();
public static Prototype CreateInstance()
{
Prototype prototype = (Prototype) _prototype.MemberwiseClone();
return prototype;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 3、三大工厂
简单工厂:不直接new对象,而是把对象创建转移到工厂类
工厂方法:屏蔽对象的创建,留下可扩展的空间
抽象工厂:屏蔽对象的创建,约束强制保障产品簇
# 4、建造者模式
复杂的工厂方法,将一个复杂对象的构造与它的表示分离,使同样的构建过程可以创建不同的表示。它是将一个复杂的对象分解为多个简单的对象,然后一步一步的构建而成,它将变与不变相分离,即产品的组成部分是不变的,但每一部分是可以灵活选择的。
# 结构型设计模式
# 1、适配器模式
解决重构的问题,新东西和旧系统不吻合,通过继承/组合进行适配。(包一层使用旧系统的形式处理新东西的内容)
class RedisHelper
{
public void AddRedis<T>(T t)
{
}
}
public class Db2Helper : IHelper
{
public void Add<T>(T t)
{
}
}
public class AdaptRedisHepler : IHelper
{
RedisHelper redisHelper=new RedisHelper();
public void Add<T>(T t)
{
redisHelper.AddRedis(t);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 2、代理模式
通过代理完成对业务类的访问,包一层方便任意功能的扩展
# 3、装饰器模式
通过组合+继承,完成对象功能的动态扩展
//基类
public abstract class AbstractStudent
{
public int Id { get; set; }
public string Name { get; set; }
public abstract void Study();
}
public class StudentVip: AbstractStudent
{
public override void Study()
{
Console.WriteLine($"{base.Name} is a Vip Student studing .net Vip");
}
}
public class BaseStudentDecorator : AbstractStudent
{
private AbstractStudent _Study = null;
public BaseStudentDecorator(AbstractStudent study)
{
this._Study = study;
}
public override void Study()
{
this._Study.Study();
}
}
public class StudentCommonDecorator : BaseStudentDecorator
{
public StudentCommonDecorator(AbstractStudent student) : base(student)
{
}
public override void Study()
{
base.Study();
Console.WriteLine("公共的内容");
}
}
public class StudentHomeWorkDecorator : BaseStudentDecorator
{
public StudentHomeWorkDecorator(AbstractStudent student) : base(student)
{
}
public override void Study()
{
base.Study();
Console.WriteLine("完成家庭作业");
}
}
public class StudentVedioDecorator:BaseStudentDecorator
{
public StudentVedioDecorator(AbstractStudent student) : base(student)
{
}
public override void Study()
{
base.Study();
Console.WriteLine("观看视频");
}
}
static void Main(string[] args)
{
AbstractStudent student = new StudentVip()
{
Id = 1,
Name = "xmn"
};
student=new BaseStudentDecorator(student);
student=new StudentCommenDecorator(student);
student = new StudentHomeWorkDecorator(student);
student=new StudentVedioDecorator(student);
student.Study(); //会调用所有的study方法,student逐层赋值
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
# 4、外观模式
外观模式又叫门面模式,是一种通过为多个复杂的子系统提供一个一致的接口,而使这些子系统更加容易被访问的模式。该模式对外有一个统一接口,外部应用程序不用关心内部子系统的具体细节,这样会大大降低应用程序的复杂度,提高了程序的可维护性。
# 5、组合模式
有时又叫整体-部分模式,它是一种将对象组合成树状的层次结构的模式,用来表示 "整体-部分" 的关系,使用户对单个对象和组合对象具有一致的访问性。
# 6、桥接模式
将抽象与实现分离,使它们可以独立变化。它是使用组合关系代替继承关系来实现,从而降低了抽象和实现者两个可变维度的耦合性。
# 7、享元模式
运用共享技术来有效地支持大量细粒度对象的数量,从而降低了系统中细粒度对象给内存带来的压力。
# 行为型设计模式
# 1、模板方法设计模式
在基类父类中定义流程,把可变的逻辑分离到不同的子类中实现
public abstract class AbstractClient
{
public void Query(int id, string name, string passward)
{
if (CheckUser(id,passward))
{
double balance = this.QueryBalance(id);
double calculate = this.CalculateInterest(balance);
this.Show(id,balance,calculate);
}
else
{
Console.WriteLine("密码错误");
}
}
public bool CheckUser(int id, string passward)
{
return DateTime.Now < DateTime.Now.AddDays(1);
}
public double QueryBalance(int id)
{
return new Random().Next(1000,1000000);
}
public void Show(int id, double balance, double calculate)
{
Console.WriteLine($"ID为{id}的用户,余额为{balance},利息为{calculate}");
}
//不同的业务逻辑
public abstract double CalculateInterest(double balance);
}
public class Client : AbstractClient
{
public new void Query(int id, string name, string passward)
{
if (CheckUser(id, passward))
{
double balance = this.QueryBalance(id);
double calculate = CalculateInterest(balance);
this.Show(id, balance, calculate);
}
else
{
Console.WriteLine("密码错误");
}
}
public new bool CheckUser(int id, string passward)
{
return DateTime.Now < DateTime.Now.AddDays(1);
}
public new double QueryBalance(int id)
{
return new Random().Next(1000, 1000000);
}
public override double CalculateInterest(double balance)
{
return balance * 0.005;
}
public new void Show(int id, double balance, double calculate)
{
Console.WriteLine($"ID为{id}的用户,余额为{balance},利息为{calculate}");
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# 2、观察者模式
一个对象动作触发多个对象的行为,通过观察者可以去掉对象的依赖,支持各种自定义和扩展
# 3、责任链模式
请求的处理流程,沿着链子顺序执行,还允许链子的扩展和定制
/// <summary>
/// Context上下文环境,保存业务处理中参数、中间结果、最终结果
/// 行为型设计模式常用的标配
/// 把行为转移,
/// </summary>
public class ApplyContext
{
public int Id { get; set; }
public string Name { get; set; }
public long Hour { get; set; }
public string Description { get; set; }
public bool AuditResult { get; set; }
public string AuditRemark { get; set; }
}
public abstract class AbstractAuditor
{
public string Name { get; set; }
public abstract void Audit(ApplyContext context);
private AbstractAuditor _NextAuditor = null;
public void SetNext(AbstractAuditor auditor)
{
this._NextAuditor = auditor;
}
protected void AuditNext(ApplyContext context)
{
_NextAuditor?.Audit(context);
}
}
public class PM: AbstractAuditor
{
public override void Audit(ApplyContext context)
{
Console.WriteLine($"This is {this.GetType().Name} {this.Name} Audit");
if (context.Hour<=8)
{
context.AuditResult = true;
context.AuditRemark = "允许请假";
}
else
{
base.AuditNext(context);
}
}
}
public class Charge: AbstractAuditor
{
public override void Audit(ApplyContext context)
{
Console.WriteLine($"This is {this.GetType().Name} {this.Name} Audit");
if (context.Hour <= 16)
{
context.AuditResult = true;
context.AuditRemark = "允许请假";
}
else
{
base.AuditNext(context);
}
}
}
public class AuditBuilder
{
public static AbstractAuditor Build()
{
PM pm = new PM()
{
Name = "111"
};
AbstractAuditor charge = new Charge()
{
Name = "xxx"
};
pm.SetNext(charge);
return pm;
}
}
static void Main(string[] args)
{
var pm = AuditBuilder.Build();
pm.Audit(context);
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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