Skip to content

Commit b49a374

Browse files
committed
设计模式
1 parent f23f0cf commit b49a374

File tree

17 files changed

+1295
-0
lines changed

17 files changed

+1295
-0
lines changed

设计模式/README.md

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
### 常用的设计模式学习记录
2+
```text
3+
├─代理模式
4+
│ proxy.py
5+
│ test.txt
6+
7+
├─单例模式
8+
│ singleton.py
9+
10+
├─外观模式
11+
│ facade.py
12+
13+
├─工厂模式
14+
│ abstract_factory.py
15+
│ factory.py
16+
│ factory_method.py
17+
18+
├─建造者模式
19+
│ builder.py
20+
21+
├─桥模式
22+
│ bridge.py
23+
24+
├─模板方法模式
25+
│ template_method.py
26+
27+
├─策略模式
28+
│ strategy.py
29+
30+
├─组合模式
31+
│ combination.py
32+
33+
├─观察者模式
34+
│ observer_pattern.py
35+
36+
├─责任链模式
37+
│ chain_responsibility.py
38+
39+
└─适配器模式
40+
adapter.py
41+
```
42+
43+
#### 常见概念
44+
1. 设计模式
45+
- 设计模式是对软件设计中普遍存在或反复出向的各种问题所提出的解决方案。每一个设计模式系统地被命名、解释和评价了面向对象系统中一个重要和重复出现的设计。
46+
47+
2. 设计模式的分类
48+
- 创建型模式:工厂方法模式、抽象工厂模式、创建者模式、原型模式、单例模式。隐藏底层模块的逻辑,关注怎么创建对象。
49+
- 结构型模式:适配器模式、桥模式、组合模式、装饰模式、外观模式、享元模式、代理模式。类之间如何协同工作,应该组成什么结构。
50+
- 行为型模式:解释器模式、责任链模式、命令模式、迭代器模式、中介者模式、备忘录模式、观察者模式、状态模式、策略模式、访问者模式、模板方法模式。关注行为,也就是方法,应该怎样某些行为。
51+
52+
3. 面向对象
53+
- 设计模式解决的就是面向对象中的问题。需要指导面向对象的三大特性是 封装、继承和多态 ,封装是把数据和方法封装到类中,继承是类之间复用代码,
54+
- 多态在Python中默认支持的,Python是一种多态的语言。
55+
56+
4. 接口
57+
- 接口是若干抽象方法的集合。接口的作用是限制实现接口的类必须按照接口给定的调用方式实现这些方法,对高层模块隐藏了类的内部实现。案例如下:
58+
```python
59+
#!/usr/bin/env python
60+
# -*- encoding: utf-8 -*-
61+
'''
62+
@File : interface.py
63+
@Time : 2022/09/12 21:21:05
64+
@Author : scliang
65+
@Desc : None
66+
'''
67+
68+
# here put the import lib
69+
# 引入抽象类
70+
from abc import ABCMeta, abstractmethod
71+
import re
72+
73+
class Payment(metaclass=ABCMeta):
74+
# abstract class
75+
@abstractmethod
76+
def pay(self,money):
77+
pass
78+
79+
80+
# 实现抽象类
81+
class AliPay(Payment):
82+
def pay(self,money):
83+
print("支付宝支付%d" %money)
84+
85+
class WechatPay(Payment):
86+
def pay(self, money):
87+
print("微信支付%d" % money)
88+
89+
# 直接实例化一个抽象类会直接报错
90+
# p = Payment()
91+
# print("abstract method:",p)
92+
'''
93+
Traceback (most recent call last):
94+
File "F:\GoProjects\src\MyPractiseNotes\设计模式\interface.py", line 33, in <module>
95+
p = Payment()
96+
TypeError: Can't instantiate abstract class Payment with abstract method pay
97+
'''
98+
99+
# 可以实例化抽象类的实现类
100+
p = AliPay()
101+
p.pay(100)
102+
103+
"""
104+
PS F:\GoProjects\src\MyPractiseNotes\设计模式> python .\interface.py
105+
支付宝支付100
106+
"""
107+
```
108+
109+
#### 面向对象的三大特性
110+
- 继承
111+
- 封装
112+
- 多态
113+
114+
#### 创建型模式
115+
- [工厂方法模式](https://github.com/scliang-strive/MyPractiseNotes/blob/master/design_patterns/%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F/factory_method.py)
116+
- [抽象工厂模式](https://github.com/scliang-strive/MyPractiseNotes/blob/master/design_patterns/%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F/abstract_factory.py)
117+
- [建造者模式](https://github.com/scliang-strive/MyPractiseNotes/blob/master/design_patterns/%E5%BB%BA%E9%80%A0%E8%80%85%E6%A8%A1%E5%BC%8F/builder.py)
118+
- 原型模式
119+
- [单例模式](https://github.com/scliang-strive/MyPractiseNotes/blob/master/design_patterns/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F/singleton.py)
120+
121+
122+
#### 结构型模式
123+
- [适配器模式](https://github.com/scliang-strive/MyPractiseNotes/blob/master/design_patterns/%E9%80%82%E9%85%8D%E5%99%A8%E6%A8%A1%E5%BC%8F/adapter.py)
124+
- [桥模式](https://github.com/scliang-strive/MyPractiseNotes/blob/master/design_patterns/%E6%A1%A5%E6%A8%A1%E5%BC%8F/bridge.py)
125+
- [组合模式](https://github.com/scliang-strive/MyPractiseNotes/blob/master/design_patterns/%E7%BB%84%E5%90%88%E6%A8%A1%E5%BC%8F/combination.py)
126+
- 装饰模式
127+
- [外观模式](https://github.com/scliang-strive/MyPractiseNotes/blob/master/design_patterns/%E5%A4%96%E8%A7%82%E6%A8%A1%E5%BC%8F/facade.py)
128+
- 享元模式
129+
- [代理模式](https://github.com/scliang-strive/MyPractiseNotes/blob/master/design_patterns/%E4%BB%A3%E7%90%86%E6%A8%A1%E5%BC%8F/proxy.py)
130+
131+
#### 行为型模式
132+
- 解释器模式
133+
- [责任链模式](https://github.com/scliang-strive/MyPractiseNotes/blob/master/design_patterns/%E8%B4%A3%E4%BB%BB%E9%93%BE%E6%A8%A1%E5%BC%8F/chain_responsibility.py)
134+
- 命令模式
135+
- 迭代器模式
136+
- 中介者模式
137+
- 备忘录模式
138+
- [观察者模式](https://github.com/scliang-strive/MyPractiseNotes/blob/master/design_patterns/%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F/observer_pattern.py)
139+
- 状态模式
140+
- [策略模式](https://github.com/scliang-strive/MyPractiseNotes/blob/master/design_patterns/%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F/strategy.py)
141+
- 访问者模式
142+
- [模板方法模式](https://github.com/scliang-strive/MyPractiseNotes/blob/master/design_patterns/%E6%A8%A1%E6%9D%BF%E6%96%B9%E6%B3%95%E6%A8%A1%E5%BC%8F/template_method.py)

设计模式/interface.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#!/usr/bin/env python
2+
# -*- encoding: utf-8 -*-
3+
'''
4+
@File : interface.py
5+
@Time : 2022/09/12 21:21:05
6+
@Author : scliang
7+
@Desc : None
8+
'''
9+
10+
# here put the import lib
11+
# 引入抽象类
12+
from abc import ABCMeta, abstractmethod
13+
import re
14+
15+
class Payment(metaclass=ABCMeta):
16+
# abstract class
17+
@abstractmethod
18+
def pay(self,money):
19+
pass
20+
21+
22+
# 实现抽象类
23+
class AliPay(Payment):
24+
def pay(self,money):
25+
print("支付宝支付%d" %money)
26+
27+
class WechatPay(Payment):
28+
def pay(self, money):
29+
print("微信支付%d元" % money)
30+
31+
32+
33+
# 直接实例化一个抽象类会直接报错
34+
# p = Payment()
35+
# print("abstract method:",p)
36+
'''
37+
Traceback (most recent call last):
38+
File "F:\GoProjects\src\MyPractiseNotes\设计模式\interface.py", line 33, in <module>
39+
p = Payment()
40+
TypeError: Can't instantiate abstract class Payment with abstract method pay
41+
'''
42+
43+
# 可以实例化抽象类的实现类
44+
p = AliPay()
45+
p.pay(100)
46+
47+
"""
48+
PS F:\GoProjects\src\MyPractiseNotes\设计模式> python .\interface.py
49+
支付宝支付100
50+
"""

设计模式/代理模式/proxy.py

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
#!/usr/bin/env python
2+
# -*- encoding: utf-8 -*-
3+
'''
4+
@File : proxy.py
5+
@Time : 2022/09/13 14:03:54
6+
@Author : scliang
7+
@Desc : 代理模式
8+
'''
9+
10+
'''
11+
为其它对象提供一种代理以控制对这个对象的访问.
12+
角色:
13+
抽象实体
14+
实体
15+
代理
16+
优点:
17+
1. 远程代理:可以隐藏对象位于远程地址空间的事实
18+
2. 虚代理:可以进行优化,例如根据要求创建对象
19+
3. 保护代理:允许访问一个对象时附加一些内务处理
20+
'''
21+
22+
# here put the import lib
23+
from abc import ABCMeta, abstractmethod
24+
25+
class Subject(metaclass=ABCMeta):
26+
@abstractmethod
27+
def get_content(self):
28+
pass
29+
30+
@abstractmethod
31+
def set_content(self, content):
32+
pass
33+
34+
# 远程代理
35+
class RealSubject(Subject):
36+
def __init__(self, filename):
37+
self.filename = filename
38+
print('读取文件内容!')
39+
with open(self.filename, 'r', encoding='utf-8') as f:
40+
self.content = f.read()
41+
42+
def get_content(self):
43+
return self.content
44+
45+
def set_content(self, content):
46+
with open(self.filename, 'w', encoding='utf-8') as f:
47+
f.write(content)
48+
49+
50+
subj = RealSubject('test.txt')
51+
'''
52+
out: 读取文件内容!
53+
'''
54+
55+
56+
57+
# 虚代理
58+
# 只有使用的时候才会实例化RealSubject(self.filename) 对象
59+
class VirtualProxy(Subject):
60+
def __init__(self, filename):
61+
self.filename = filename
62+
self.subj = None
63+
64+
def get_content(self):
65+
if not self.subj:
66+
self.subj = RealSubject(self.filename)
67+
return self.subj.get_content()
68+
69+
def set_content(self, content):
70+
if not self.subj:
71+
self.subj = RealSubject(self.filename)
72+
73+
return self.subj.set_content(content)
74+
75+
subj = VirtualProxy('test.txt')
76+
print(subj.get_content())
77+
'''
78+
out:
79+
读取文件内容!
80+
testting....
81+
'''
82+
83+
84+
# 保护代理
85+
class ProtectedSubject(Subject):
86+
def __init__(self, filename):
87+
self.subj = RealSubject(filename)
88+
89+
def get_content(self):
90+
return self.subj.get_content()
91+
92+
def set_content(self, content):
93+
raise PermissionError('无写入权限!')
94+
95+
subj = ProtectedSubject('test.txt')
96+
print(subj.get_content())
97+
subj.set_content('abc')
98+
99+
'''
100+
out:
101+
取文件内容!
102+
testting....
103+
Traceback (most recent call last):
104+
File "F:\GoProjects\src\MyPractiseNotes\设计模式\代理模式\proxy.py", line 89, in <module>
105+
subj.set_content('abc')
106+
File "F:\GoProjects\src\MyPractiseNotes\设计模式\代理模式\proxy.py", line 85, in set_content
107+
raise PermissionError('无写入权限!')
108+
PermissionError: 无写入权限!
109+
'''

设计模式/代理模式/test.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
testting....
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#!/usr/bin/env python
2+
# -*- encoding: utf-8 -*-
3+
'''
4+
@File : singleton.py
5+
@Time : 2022/09/12 21:13:18
6+
@Author : scliang
7+
@Desc : 单例模式
8+
'''
9+
10+
'''
11+
保证一个类只有一个实例,并提供一个放问它的全局访问点.
12+
角色:
13+
单例
14+
优点:
15+
1. 对唯一实例的受控访问.
16+
2. 单例相当于全局变量,但防止了命名空间被污染.
17+
'''
18+
19+
20+
# here put the import lib
21+
22+
class SingletonPattern():
23+
def __new__(cls: type[Self]) -> Self:
24+
if not hasattr(cls,"_instance"):
25+
cls._instance = super(SingletonPattern,cls).__new__(cls)
26+
return cls._instance
27+
28+
class MyClass(SingletonPattern):
29+
def __init__(self,number) -> None:
30+
self.number = number
31+
32+
33+
# client
34+
n1 = MyClass(100)
35+
n2 = MyClass(200)
36+
37+
# n1,n2 是返回的同一个实例,但是n2后修改,所以修改了全局实例对象的值
38+
print(n1) # 200
39+
print(n2) # 200
40+
41+
# 查看是否是用一个对象
42+
print(id(n1) == id(n2)) # True

0 commit comments

Comments
 (0)