python16_day34【设计模式】
一、简单工厂模式
# coding : utf-8
# create by ztypl on 2017/5/24 from abc import abstractmethod, ABCMeta class Payment(metaclass=ABCMeta):
@abstractmethod
def pay(self, money):
pass class Alipay(Payment):
def __init__(self, enable_yuebao=False):
self.enable_yuebao = enable_yuebao def pay(self, money):
if self.enable_yuebao:
print("余额宝支付%s元" % money)
else:
print("支付宝支付%s元" % money) class ApplePay(Payment):
def pay(self, money):
print("苹果支付%s元" % money) class PaymentFactory:
def create_payment(self, method):
if method == "alipay":
return Alipay()
elif method == "applepay":
return ApplePay()
elif method == "yuebao":
return Alipay(enable_yuebao=True)
else:
raise NameError(method) f = PaymentFactory()
p = f.create_payment("alipay")
p.pay(100)
二、工厂模式
from abc import abstractmethod, ABCMeta class Payment(metaclass=ABCMeta):
@abstractmethod
def pay(self, money):
pass class Alipay(Payment):
def pay(self, money):
print("支付宝支付%s元" % money) class ApplePay(Payment):
def pay(self, money):
print("苹果支付%s元"%money) class PaymentFactory(metaclass=ABCMeta):
@abstractmethod
def create_payment(self):
pass class AlipayFactory(PaymentFactory):
def create_payment(self):
return Alipay() class ApplePayFactory(PaymentFactory):
def create_payment(self):
return ApplePay() # 用户输入
# 支付宝,120 af = AlipayFactory()
ali = af.create_payment()
ali.pay(120)
三、抽象工厂模式
rom abc import abstractmethod, ABCMeta # ------抽象产品------
class PhoneShell(metaclass=ABCMeta):
@abstractmethod
def show_shell(self):
pass class CPU(metaclass=ABCMeta):
@abstractmethod
def show_cpu(self):
pass class OS(metaclass=ABCMeta):
@abstractmethod
def show_os(self):
pass # ------抽象工厂------ class PhoneFactory(metaclass=ABCMeta):
@abstractmethod
def make_shell(self):
pass @abstractmethod
def make_cpu(self):
pass @abstractmethod
def make_os(self):
pass # ------具体产品------ class SmallShell(PhoneShell):
def show_shell(self):
print("普通手机小手机壳") class BigShell(PhoneShell):
def show_shell(self):
print("普通手机大手机壳") class AppleShell(PhoneShell):
def show_shell(self):
print("苹果手机壳") class SnapDragonCPU(CPU):
def show_cpu(self):
print("骁龙CPU") class MediaTekCPU(CPU):
def show_cpu(self):
print("联发科CPU") class AppleCPU(CPU):
def show_cpu(self):
print("苹果CPU") class Android(OS):
def show_os(self):
print("Android系统") class IOS(OS):
def show_os(self):
print("iOS系统") # ------具体工厂------ class MiFactory(PhoneFactory):
def make_cpu(self):
return SnapDragonCPU() def make_os(self):
return Android() def make_shell(self):
return BigShell() class HuaweiFactory(PhoneFactory):
def make_cpu(self):
return MediaTekCPU() def make_os(self):
return Android() def make_shell(self):
return SmallShell() class IPhoneFactory(PhoneFactory):
def make_cpu(self):
return AppleCPU() def make_os(self):
return IOS() def make_shell(self):
return AppleShell() # ------客户端------ class Phone:
def __init__(self, cpu, os, shell):
self.cpu = cpu
self.os = os
self.shell = shell def show_info(self):
print("手机信息:")
self.cpu.show_cpu()
self.os.show_os()
self.shell.show_shell() def make_phone(factory):
cpu = factory.make_cpu()
os = factory.make_os()
shell = factory.make_shell()
return Phone(cpu, os, shell) p1 = make_phone(HuaweiFactory())
p1.show_info()
四、建筑者模式
from abc import abstractmethod, ABCMeta #------产品------ class Player:
def __init__(self, face=None, body=None, arm=None, leg=None):
self.face = face
self.arm = arm
self.leg = leg
self.body = body def __str__(self):
return "%s, %s, %s, %s" % (self.face, self.arm, self.body, self.leg) #------建造者------ class PlayerBuilder(metaclass=ABCMeta):
@abstractmethod
def build_face(self):
pass
@abstractmethod
def build_arm(self):
pass
@abstractmethod
def build_leg(self):
pass
@abstractmethod
def build_body(self):
pass
@abstractmethod
def get_player(self):
pass class BeautifulWomanBuilder(PlayerBuilder):
def __init__(self):
self.player = Player()
def build_face(self):
self.player.face = "漂亮脸蛋"
def build_arm(self):
self.player.arm="细胳膊"
def build_body(self):
self.player.body="细腰"
def build_leg(self):
self.player.leg="长腿"
def get_player(self):
return self.player class PlayerDirector:
def build_player(self, builder):
builder.build_body()
builder.build_arm()
builder.build_leg()
builder.build_face()
return builder.get_player() director = PlayerDirector()
builder = BeautifulWomanBuilder()
p = director.build_player(builder)
print(p)
五、单例模式
需要先看懂__new__这个方法 from abc import abstractmethod, ABCMeta class Singleton(object):
def __new__(cls, *args, **kwargs):
# 第一次返回_instance这个实后,后续返回相同的。
if not hasattr(cls, "_instance"):
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance class MyClass(Singleton):
def __init__(self, name):
self.name = name a = MyClass("a") print(a)
print(a.name) b = MyClass('b')
#
print(b)
print(b.name)
b.name = 'xxx'
#
print(a)
print(a.name)
六、适配器模式
# coding : utf-8
# create by ztypl on 2017/5/25 from abc import abstractmethod, ABCMeta class Payment(metaclass=ABCMeta):
@abstractmethod
def pay(self, money):
raise NotImplementedError class Alipay(Payment):
def pay(self, money):
print("支付宝支付%s元"%money) class ApplePay(Payment):
def pay(self, money):
print("苹果支付%s元"%money) #------待适配类------ class WechatPay:
def huaqian(self, money):
print("微信支付%s元"%money) # 方法一
#------类适配器------ class RealWeChatPay(Payment, WechatPay):
def pay(self, money):
return self.huaqian(money) # 方法二
#------对象适配器------
class PayAdapter(Payment):
def __init__(self, payment):
self.payment = payment def pay(self, money):
return self.payment.huaqian(money) # client
RealWeChatPay().pay(100)
#PayAdapter(WechatPay()).pay(1000)
七、复合模式
# coding : utf-8
# create by ztypl on 2017/5/25 from abc import abstractmethod, ABCMeta class Graphic(metaclass=ABCMeta):
@abstractmethod
def draw(self):
pass @abstractmethod
def add(self, graphic):
pass def getchildren(self):
pass # 图元 class Point(Graphic):
def __init__(self, x, y):
self.x = x
self.y = y def draw(self):
print(self) def add(self, graphic):
raise TypeError def getchildren(self):
raise TypeError def __str__(self):
return "点(%s, %s)" % (self.x, self.y) class Line(Graphic):
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2 def draw(self):
print(self) def add(self, graphic):
raise TypeError def getchildren(self):
raise TypeError def __str__(self):
return "线段[%s, %s]" % (self.p1, self.p2) class Picture(Graphic):
def __init__(self):
self.children = [] def add(self, graphic):
self.children.append(graphic) def getchildren(self):
return self.children def draw(self):
print("------复合图形------")
for g in self.children:
g.draw()
print("------END------") pic1 = Picture()
point = Point(2,3)
pic1.add(point)
pic1.add(Line(Point(1,2), Point(4,5)))
pic1.add(Line(Point(0,1), Point(2,1))) pic2 = Picture()
pic2.add(Point(-2,-1))
pic2.add(Line(Point(0,0), Point(1,1))) pic = Picture()
pic.add(pic1)
pic.add(pic2) pic.draw()
#pic1.draw()
#point.draw()
八、代理模式
# coding : utf-8
# create by ztypl on 2017/5/26 from abc import ABCMeta, abstractmethod class Subject(metaclass=ABCMeta):
@abstractmethod
def get_content(self):
pass
def set_content(self, content):
pass class RealSubject(Subject):
def __init__(self, filename):
self.filename = filename
print("读取%s文件内容"%filename)
f = open(filename)
self.content = f.read()
f.close() def get_content(self):
return self.content def set_content(self, content):
f = open(self.filename, 'w')
f.write(content)
self.content = content
f.close() class ProxyA(Subject):
def __init__(self, filename):
self.subj = RealSubject(filename) def get_content(self):
return self.subj.get_content() #---虚代理
class ProxyB(Subject):
def __init__(self, filename):
self.filename = filename
self.subj = None def get_content(self):
if not self.subj:
self.subj = RealSubject(self.filename)
return self.subj.get_content() x = ProxyB('abc.txt')
#print(x.get_content()) class ProxyC(Subject):
def __init__(self, filename):
self.subj = RealSubject(filename) def get_content(self):
self.subj.get_content() def set_content(self, content):
raise PermissionError # filename = "abc.txt"
# username = input()
# if username!="alex":
# p = ProxyC(filename)
# else:
# p = ProxyA(filename)
#
# print(p.get_content())
九、链式模式
from abc import ABCMeta, abstractmethod class Handler(metaclass=ABCMeta):
@abstractmethod
def handle_leave(self, day):
pass class GeneralManagerHandler(Handler):
def handle_leave(self, day):
if day < 10:
print("总经理批准%d天假"%day)
else:
print("呵呵") class DepartmentManagerHandler(Handler):
def __init__(self):
self.successor = GeneralManagerHandler()
def handle_leave(self, day):
if day < 7:
print("部门经理批准%d天假"%day)
else:
print("部门经理无权准假")
self.successor.handle_leave(day) class ProjectDirectorHandler(Handler):
def __init__(self):
self.successor = DepartmentManagerHandler()
def handle_leave(self, day):
if day < 3:
print("项目主管批准%d天假"%day)
else:
print("项目主管无权准假")
self.successor.handle_leave(day) day = 9
h = ProjectDirectorHandler()
h.handle_leave(day)
十、迭代模式
# coding : utf-8
# create by ztypl on 2017/5/27 class LinkList:
"""链表 头结点保存链表的长度"""
class Node:
def __init__(self, item=None):
self.item = item
self.next = None class LinkListIterator:
def __init__(self, node):
self.node = node
def __next__(self):
if self.node:
cur_node = self.node
self.node = cur_node.next
return cur_node.item
else:
raise StopIteration
def __iter__(self):
return self def __init__(self, iterable=None):
self.head = LinkList.Node(0)
self.tail = self.head
self.extend(iterable) def append(self, obj):
s = LinkList.Node(obj)
self.tail.next = s
self.tail = s def extend(self, iterable):
for obj in iterable:
self.append(obj)
self.head.item += len(iterable) def __iter__(self):
return self.LinkListIterator(self.head.next) def __len__(self):
return self.head.item def __str__(self):
return "<<" + ", ".join(map(str, self)) + ">>" li = [i for i in range(100)]
lk = LinkList(li)
print(lk)
十一、观察者模式(发布订阅)
# coding : utf-8
# create by ztypl on 2017/5/27 from abc import ABCMeta, abstractmethod class Observer(metaclass=ABCMeta):
@abstractmethod
def update(self, notice):
pass class Notice:
def __init__(self):
self.observers = [] def attach(self, obs):
self.observers.append(obs) def detach(self, obs):
self.observers.remove(obs)
obs.company_info=None def notify(self):
for obj in self.observers:
print("---", type(self))
obj.update(self) #这个self是ManagerNotice对象 class ManagerNotice(Notice):
def __init__(self, company_info=None):
super().__init__()
self.__company_info = company_info @property
def company_info(self):
return self.__company_info @company_info.setter
def company_info(self, info):
self.__company_info = info
self.notify() class Manager(Observer):
def __init__(self):
self.company_info = None def update(self, noti):
self.company_info = noti.company_info # 拿到最新消息保存到对象中(alex,wusir) notice = ManagerNotice() alex = Manager()
wusir = Manager() # print(alex.company_info)
# print(wusir.company_info) notice.attach(alex)
notice.attach(wusir)
#
notice.company_info="公司运行良好"
#
print(alex.company_info)
print(wusir.company_info) notice.company_info="公司将要上市"
#
print(alex.company_info)
print(wusir.company_info)
# #
notice.detach(wusir)
# # #
notice.company_info="公司要破产了,赶快跑路"
# #
print(alex.company_info)
print(wusir.company_info)
十二、策略模式
# coding : utf-8
# create by ztypl on 2017/5/27 from abc import ABCMeta, abstractmethod
import random class Sort(metaclass=ABCMeta):
@abstractmethod
def sort(self, data):
pass class QuickSort(Sort):
def quick_sort(self, data, left, right):
if left < right:
mid = self.partition(data, left, right)
self.quick_sort(data, left, mid - 1)
self.quick_sort(data, mid + 1, right) def partition(self, data, left, right):
tmp = data[left]
while left < right:
while left < right and data[right] >= tmp:
right -= 1
data[left] = data[right]
while left < right and data[left] <= tmp:
left += 1
data[right] = data[left]
data[left] = tmp
return left def sort(self, data):
print("快速排序")
return self.quick_sort(data, 0, len(data) - 1) class MergeSort(Sort):
def merge(self, data, low, mid, high):
i = low
j = mid + 1
ltmp = []
while i <= mid and j <= high:
if data[i] <= data[j]:
ltmp.append(data[i])
i += 1
else:
ltmp.append(data[j])
j += 1 while i <= mid:
ltmp.append(data[i])
i += 1 while j <= high:
ltmp.append(data[j])
j += 1 data[low:high + 1] = ltmp def merge_sort(self, data, low, high):
if low < high:
mid = (low + high) // 2
self.merge_sort(data, low, mid)
self.merge_sort(data, mid + 1, high)
self.merge(data, low, mid, high) def sort(self, data):
print("归并排序")
return self.merge_sort(data, 0, len(data) - 1) class Context:
def __init__(self, data, strategy=None):
self.data = data
self.strategy = strategy def set_strategy(self, strategy):
self.strategy = strategy def do_strategy(self):
if self.strategy:
self.strategy.sort(self.data)
else:
raise TypeError li = list(range(100000))
random.shuffle(li) context = Context(li, MergeSort())
context.do_strategy()
#print(context.data) random.shuffle(context.data) context.set_strategy(QuickSort())
context.do_strategy()
十三、模板方法模式
# coding : utf-8
# create by ztypl on 2017/5/27 from abc import ABCMeta, abstractmethod class IOHandler(metaclass=ABCMeta):
@abstractmethod
def open(self, name):
pass
@abstractmethod
def deal(self, change):
pass
@abstractmethod
def close(self):
pass
def process(self, name, change):
self.open(name)
self.deal(change)
self.close() class FileHandler(IOHandler):
def open(self, name):
self.file = open(name,"w") def deal(self, change):
self.file.write(change) def close(self):
self.file.close() f = FileHandler()
f.process("abc.txt", "Hello World")
python16_day34【设计模式】的更多相关文章
- MVVM设计模式和WPF中的实现(四)事件绑定
MVVM设计模式和在WPF中的实现(四) 事件绑定 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在WPF中 ...
- java EE设计模式简介
1.何为设计模式 设计模式提供了对常见应用设计问题的解决方案.在面向对象的编程中,设计模式通常在解决与对象创建和交互相关的问题,而非整体软件架构所面对的大规模问题,它们以样板代码的形式提供了通用的解决 ...
- 计算机程序的思维逻辑 (54) - 剖析Collections - 设计模式
上节我们提到,类Collections中大概有两类功能,第一类是对容器接口对象进行操作,第二类是返回一个容器接口对象,上节我们介绍了第一类,本节我们介绍第二类. 第二类方法大概可以分为两组: 接受其他 ...
- 《JavaScript设计模式 张》整理
最近在研读另外一本关于设计模式的书<JavaScript设计模式>,这本书中描述了更多的设计模式. 一.创建型设计模式 包括简单工厂.工厂方法.抽象工厂.建造者.原型和单例模式. 1)简单 ...
- 《JavaScript设计模式与开发实践》整理
最近在研读一本书<JavaScript设计模式与开发实践>,进阶用的. 一.高阶函数 高阶函数是指至少满足下列条件之一的函数. 1. 函数可以作为参数被传递. 2. 函数可以作为返回值输出 ...
- 设计模式之行为类模式大PK
行为类模式大PK 行为类模式包括责任链模式.命令模式.解释器模式.迭代器模式.中介者模式.备忘录模式.观察者模式.状态模式.策略 ...
- .NET设计模式访问者模式
一.访问者模式的定义: 表示一个作用于某对象结构中的各元素的操作.它使你可以在不改变各元素类的前提下定义作用于这些元素的新操作. 二.访问者模式的结构和角色: 1.Visitor 抽象访问者角色,为该 ...
- Java开发中的23种设计模式详解
[放弃了原文访问者模式的Demo,自己写了一个新使用场景的Demo,加上了自己的理解] [源码地址:https://github.com/leon66666/DesignPattern] 一.设计模式 ...
- java 设计模式
目录: 设计模式六大原则(1):单一职责原则 设计模式六大原则(2):里氏替换原则 设计模式六大原则(3):依赖倒置原则 设计模式六大原则(4):接口隔离原则 设计模式六大原则(5):迪米特法则 设计 ...
随机推荐
- [java] java 中Unsafe类学习
java不能直接访问操作系统底层,而是通过本地方法来访问.Unsafe类提供了硬件级别的原子操作,主要提供了以下功能: 1.通过Unsafe类可以分配内存,可以释放内存: 类中提供的3个本地方法all ...
- QQ第三方登录实例demo(QQSDK包优化)
实现效果: 实现流程: 1.注冊QQ互联开发人员 QQ互联官网 注冊成为开发人员(须要审核) 2.审核通过之后 申请应用(须要互联人员审核*须要备案成功的线上域名) 以下我们開始下载QQsdk包 QQ ...
- UVA 1341 - Different Digits(数论)
UVA 1341 - Different Digits 题目链接 题意:给定一个正整数n.求一个kn使得kn上用的数字最少.假设同样,则输出值最小的 思路: 首先利用鸽笼原理证明最多须要2个数字去组成 ...
- python2.0_s12_day9_mysql操作
mysql的基本语法: 1.数据库操作 show databases; create database 数据库名;如果想允许数据库可以写中文create database 数据库名 charset u ...
- Android中Parcelable和Serializable接口用法
1. Parcelable接口 Interface for classes whose instances can be written to and restored from a Parcel. ...
- #pragam预处理分析
#pragma是编译器指示字,用域指示编译器完成一些特定动作, #pragma所定义的很多指示字是编译器和操作系统特有的 #pragma在不同的编译器间是不可移植的 预处理器将忽略它不认识的#prag ...
- 微信accesstoken回调
errcode=-1的时候,开发文档中说明是系统异常,至于具体原因不明 不过有一种原因是AppID以及AppSecret错误 其它可能原因还待发现
- [转]C++结构体|类 内存对齐详解
内存地址对齐,是一种在计算机内存中排列数据(表现为变量的地址).访问数据(表现为CPU读取数据)的一种方式,包含了两种相互独立又相互关联的部分:基本数据对齐和结构体数据对齐 . 为什么需要内存对齐?对 ...
- 腾讯云大数据套件Hermes-MR索引插件使用总结
版权声明:本文由王亮原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/121 来源:腾云阁 https://www.qclou ...
- 日志系统实战 AOP静态注入
http://www.cnblogs.com/mushroom/p/3932698.html http://www.cnblogs.com/mushroom/p/4124878.html http:/ ...