一、简单工厂模式

 # 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【设计模式】的更多相关文章

  1. MVVM设计模式和WPF中的实现(四)事件绑定

    MVVM设计模式和在WPF中的实现(四) 事件绑定 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在WPF中 ...

  2. java EE设计模式简介

    1.何为设计模式 设计模式提供了对常见应用设计问题的解决方案.在面向对象的编程中,设计模式通常在解决与对象创建和交互相关的问题,而非整体软件架构所面对的大规模问题,它们以样板代码的形式提供了通用的解决 ...

  3. 计算机程序的思维逻辑 (54) - 剖析Collections - 设计模式

    上节我们提到,类Collections中大概有两类功能,第一类是对容器接口对象进行操作,第二类是返回一个容器接口对象,上节我们介绍了第一类,本节我们介绍第二类. 第二类方法大概可以分为两组: 接受其他 ...

  4. 《JavaScript设计模式 张》整理

    最近在研读另外一本关于设计模式的书<JavaScript设计模式>,这本书中描述了更多的设计模式. 一.创建型设计模式 包括简单工厂.工厂方法.抽象工厂.建造者.原型和单例模式. 1)简单 ...

  5. 《JavaScript设计模式与开发实践》整理

    最近在研读一本书<JavaScript设计模式与开发实践>,进阶用的. 一.高阶函数 高阶函数是指至少满足下列条件之一的函数. 1. 函数可以作为参数被传递. 2. 函数可以作为返回值输出 ...

  6. 设计模式之行为类模式大PK

                                        行为类模式大PK 行为类模式包括责任链模式.命令模式.解释器模式.迭代器模式.中介者模式.备忘录模式.观察者模式.状态模式.策略 ...

  7. .NET设计模式访问者模式

    一.访问者模式的定义: 表示一个作用于某对象结构中的各元素的操作.它使你可以在不改变各元素类的前提下定义作用于这些元素的新操作. 二.访问者模式的结构和角色: 1.Visitor 抽象访问者角色,为该 ...

  8. Java开发中的23种设计模式详解

    [放弃了原文访问者模式的Demo,自己写了一个新使用场景的Demo,加上了自己的理解] [源码地址:https://github.com/leon66666/DesignPattern] 一.设计模式 ...

  9. java 设计模式

    目录: 设计模式六大原则(1):单一职责原则 设计模式六大原则(2):里氏替换原则 设计模式六大原则(3):依赖倒置原则 设计模式六大原则(4):接口隔离原则 设计模式六大原则(5):迪米特法则 设计 ...

随机推荐

  1. Makefile--伪目标 (三)

    原创博文,转载请标明出处--周学伟http://www.cnblogs.com/zxouxuewei/ 一般情况下,Makefile都会有一个clean目标,用于清除编译过程中产生的二进制文件.我们在 ...

  2. python--dict和set类型--4

    原创博文,转载请标明出处--周学伟http://www.cnblogs.com/zxouxuewei/ 一.什么是dict 我们已经知道,list 和 tuple 可以用来表示顺序集合,例如,班里同学 ...

  3. Python 爬虫实战

    图片爬虫实战 链接爬虫实战 糗事百科爬虫实战 微信爬虫实战 多线程爬虫实战

  4. Eclipse版GoogleI/O2014开源项目

    https://github.com/google/iosched谷歌原版是Gradle工程,用Eclipse开发的导入不了,所以搞了一个Elicpse工程,依赖的jar.库比较多,也比较难找... ...

  5. 【Mysql】大数据处理优化方法

    1.应尽量避免在 where 子句中使用 != 或  <>  操作符,否则将引擎放弃使用索引而进行全表扫描. 2.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 orde ...

  6. BNU4206:单向行走

    给定一个m*n的矩阵,请写一个程序计算一条从左到右走过矩阵且权和最小的路径.一条路径可以从第1列的任意位置出发,到达第n列的任意位置.每一步只能从第i列走到第i+1列的同一行或者相邻行(第一行和最后一 ...

  7. Docker源码分析(四):Docker Daemon之NewDaemon实现

    1. 前言 Docker的生态系统日趋完善,开发者群体也在日趋庞大,这让业界对Docker持续抱有极其乐观的态度.如今,对于广大开发者而言,使用Docker这项技术已然不是门槛,享受Docker带来的 ...

  8. LeetCode——Search a 2D Matrix II

    Description: Write an efficient algorithm that searches for a value in an m x n matrix. This matrix ...

  9. LeetCode——Number of 1 Bits

    //求一个整数的二进制串中1的个数 public int hammingWeight(int n) { String b_str = Integer.toBinaryString(n); int b_ ...

  10. ubuntu android studio kvm

    Android studio 启动模拟器失败: Cannot launch AVD in emulator.Output:emulator: ERROR: x86 emulation currentl ...