-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAdapter.py
More file actions
87 lines (62 loc) · 1.49 KB
/
Adapter.py
File metadata and controls
87 lines (62 loc) · 1.49 KB
1
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
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Time : 2022/08/18 19:48:38
# @Author : Gary
# @Email : None
# 类适配器模式使用示例:
from abc import ABCMeta, abstractmethod
class Payment(object, metaclass=ABCMeta):
# 目标接口
@abstractmethod
def pay(self, money):
pass
class Alipay(Payment):
def pay(self, money):
print('支付了%d' % money)
class BankPay():
# 待适配的类
def cost(self, money):
print('银联支付了%d' % money)
class PaymentAdapter(Payment, BankPay):
# 类适配器
"""
把不兼容cost转换成pay
"""
def pay(self, money):
self.cost(money)
p = PaymentAdapter()
p.pay(100)
"""
银联支付了100
"""
# 类适配器模式使用示例:
class Payment(object, metaclass=ABCMeta):
# 目标接口
@abstractmethod
def pay(self, money):
pass
class Alipay(Payment):
def pay(self, money):
print('支付了%d' % money)
class BankPay():
# 待适配的类
def cost(self, money):
print('银联支付了%d' % money)
class ApplePay():
# 待适配的类
def cost(self, money):
print('苹果支付了%d' % money)
class PaymentAdapter(Payment):
# 对象适配器
def __init__(self, payment):
self.payment = payment
def pay(self, money):
self.payment.cost(money)
p = PaymentAdapter(ApplePay())
p.pay(100)
p = PaymentAdapter(BankPay())
p.pay(100)
"""
苹果支付了100
银联支付了100
"""