适配器设计模式
什么是适配器模式
适配器就是是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。
有什么优缺点
优点:
1. 可以让两个没有关联的类一起运行,器中间转换作用
2. 可以提高类的复用率
3. 灵活性好,不会破坏原由的系统
缺点:
1. 过多地使用适配器,会让系统非常零乱,不易整体进行把握
UML类图
![在这里插入图片描述](https://img-blog.csdnimg.cn/91d3b21873384577b6a5e9ad747fce73.png)
例子就以google支付来看
from functools import partial
import json, requests
class GoogleGetResource():
"""
从Google接口获取商品的信息
custom_url:str Google API 的调用地址
default: https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{package_name}/purchases/products/{goods_id}/tokens/{pay_token}
package_name:str 应用程序的包名
goods_id:str Google商店配置的商品ID
pay_token:str 客户端提交的购买密钥
access_token:str 访问API的授权码
"""
def __init__(self, package_name:str, goods_id:str, pay_token:str, access_token:str, custom_url:str=None):
if custom_url == None:
self._custom_url = f"https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{package_name}/purchases/products/{goods_id}/tokens/{pay_token}"
else:
self._custom_url = custom_url.format(package_name, goods_id, pay_token)
self._params = {
'access_token': access_token
}
class GoogleGetAcknowledgeState():
"""
确认商品购买有效
custom_url:str Google API 的调用地址
default: https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{package_name}/purchases/products/{goods_id}/tokens/{pay_token}:acknowledge?access_token={access_token}
package_name:str 应用程序包名
goods_id:str Google商店配置的商品ID
pay_token:str 客户端提交的购买密钥
developer_payload: get_resource返回的对象中包含的developerPayload字段
access_token:str 访问API的授权码
"""
def __init__(self, package_name:str, goods_id:str, pay_token:str, developer_payload:str, access_token:str, custom_url:str=None):
if not custom_url:
self._custom_url = f"https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{package_name}/purchases/products/{goods_id}/tokens/{pay_token}:acknowledge?access_token={access_token}"
else:
self._custom_url = custom_url.format(package_name,goods_id,pay_token,access_token)
self._params = {}
class AdapterBindClass:
def __new__(cls, pay_object:object, method:str):
target = PublicRequest(url = pay_object._custom_url, params = pay_object._params)
if method == 'post':
return partial(
PublicRequest.post,
target
)
else:
return partial(
PublicRequest.get,
target
)
class PublicRequest():
def __init__(self, url:str, params:str):
self._url = url
self._params = params
self._headers = {"Content-Type": "application/json"}
def post(self):
res = None
try:
if self._params:
params = json.dumps(self._params)
res = requests.post(url = self._url, headers = self._headers, data = params)
else:
res = requests.post(url = self._url, headers = self._headers)
if res.text:
response = json.loads(res.text)
error = response.get("error",None)
if error:
print("获取RequestAPI失败 response error: {error}".format(error = error))
return None
else:
return response
else:
if isinstance(res.text, str):
return res.text
if isinstance(res.text, bytes):
return res.text.decode("utf-8")
if isinstance(res.text, dict) or isinstance(res.text, list):
return json.loads(res.text)
except Exception as e:
print('post {url} request error {e} params is {params}'.
format(url=self._url, e=e, params = self._params))
return None
def get(self):
resp = None
try:
if self._params:
resp = requests.get(url = self._url, headers = self._headers, params = self._params)
else:
resp = requests.get(url = self._url, headers = self._headers)
if resp.status_code == 200 or resp.status_code == 204:
content = json.loads(resp.text)
if content.get('error'):
error = content['error']
print(f"RequestAPI失败\nurl={self._url}\nstatus={resp.status_code}\nerror: {error}")
return None
else:
print(f"RequestAPI成功\n URL = {self._url}")
return content
else:
print(f"RequestAPI失败\nurl={self._url}\nstatus={resp.status_code}\ntext: {resp.text}")
return None
except Exception as e:
print('get {url} request error {e} params is {params}'.format(url = self._url, e = e, params = self._params))
return None