python设计模式
设计模式分类:
创建型模式(5种):工厂方法模式、抽象工厂模式、创建者模式、(原型模式)、单例模式
结构型模式(7种):适配器模式、桥模式、组合模式、装饰模式、外观模式、享元模式、代理模式
行为型模式(11种):解释器模式、责任链模式、命令模式、迭代器模式、中介者模式、备忘录模式、观察者模式、状态模式、策略模式、访问者模式、模版方法模式
提示:以下是本篇文章正文内容,下面案例可供参考
控制类组成结构
from abc import ABCMeta, abstractmethod
class Shape(metaclass=ABCMeta):
def __init__(self, color):
self.color = color
@abstractmethod
def draw(self):
pass
class Color(metaclass=ABCMeta):
@abstractmethod
def paint(self, shape):
pass
class Rectangle(Shape):
name = "长方形"
def draw(self):
self.color.paint(self)
class Circle(Shape):
name = "圆形"
def draw(self):
self.color.paint(self)
class Red(Color):
def paint(self,shape):
print("红色的%s"%shape.name)
class Green(Color):
def paint(self,shape):
print("绿色的%s"%shape.name)
shape = Rectangle(Red())
shape.draw()
from abc import ABCMeta, abstractmethod
# 抽象组件
class Graphic(metaclass=ABCMeta):
@abstractmethod
def draw(self):
pass
# 叶子组件
class Point(Graphic):
def __init__(self,x,y):
self.x = x
self.y = y
def __str__(self):
return "点(%s, %s)"%(self.x, self.y)
def draw(self):
print(str(self))
# 叶子组件
class Line(Graphic):
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def __str__(self):
return "线段[%s, %s]" %(self.p1, self.p2)
def draw(self):
print(str(self))
# 复合组件
class Picture(Graphic):
def __init__(self, iterable):
self.children = []
for g in iterable:
self.add(g)
def add(self,graphic):
self.children.append(graphic)
def draw(self):
print("----复合图形----")
for g in self.children:
g.draw()
print("----复合图形----")
l = Line(Point(1,1),Point(2,2))
print(l)
l.draw()
p1 = Point(2,3)
l1 = Line(Point(3,4),Point(6,7))
l2 = Line(Point(1,5),Point(2,8))
pic1 = Picture([p1,l1,l2])
pic1.draw()
from abc import ABCMeta, abstractmethod
class Handler(metaclass=ABCMeta):
@abstractmethod
def handle_level(self, day):
pass
class GeneralManager(Handler):
def handle_level(self, day):
if day < 10:
print("总理经准假%d天"%day)
else:
print("请假超过10天,你还是辞职吧")
class DepartmentManager(Handler):
def __init__(self):
self.next = GeneralManager()
def handle_level(self, day):
if day <=5:
print("部门经理准假%d天"%day)
else:
print("部门经理职权不足")
self.next.handle_level(day)
class ProjectDirector(Handler):
def __init__(self):
self.next = DepartmentManager()
def handle_level(self, day):
if day<=3:
print("项目主管准假%d天"%day)
else:
print("项目主管职权不足")
self.next.handle_level(day)
# 高层代码 client
day = 8
h = ProjectDirector()
h.handle_level(day)
from abc import ABCMeta, abstractmethod
class Observer(metaclass=ABCMeta): # 抽象订阅者
@abstractmethod
def update(self, notice): # notice 是一个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)
def notify(self): # 推送
for obs in self.observers:
obs.update(self)
class StaffNotice(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 Staff(Observer):
def __init__(self):
self.company_info = None
def update(self, notice):
self.company_info = notice.company_info
# Client
notice = StaffNotice("初始公司信息")
s1 = Staff()
s2 = Staff()
notice.attach(s1)
notice.attach(s2)
print(s1.company_info) # None
notice.company_info = "公司今年业绩非常好,给大家发奖金"
print(s1.company_info) # 被修改了
print(s2.company_info) # 被修改了
notice.detach(s2)
notice.company_info = "公司明天放假"
print(s1.company_info) # 被修改了
print(s2.company_info) # 没有被修改
from abc import ABCMeta, abstractmethod
class Strategy(metaclass=ABCMeta):
@abstractmethod
def execute(self, data):
pass
class FastStrategy(Strategy):
def execute(self, data):
print("用较快的策略处理%s"%data)
class SlowStrategy(Strategy):
def execute(self, data):
print("用较慢的策略处理%s" % data)
class Context:
def __init__(self,data,strategy):
self.data = data
self.strategy = strategy
def set_strategy(self, strategy):
self.strategy = strategy
def do_strategy(self):
self.strategy.execute(self.data)
# Client
data = "[...]"
s1 = FastStrategy()
s2 = SlowStrategy()
context = Context(data,s1)
context.do_strategy()
context.set_strategy(s2)
context.do_strategy()
from abc import ABCMeta,abstractmethod
from time import sleep
class Window(metaclass=ABCMeta):
@abstractmethod
def star(self):
pass
@abstractmethod
def repaint(self):
pass
@abstractmethod
def stop(self):
pass
def run(self): # 模板方法
self.star()
while True:
try:
self.repaint()
sleep(1)
except KeyboardInterrupt:
break
self.stop()
class MyWindow(Window):
def __init__(self,msg):
self.msg = msg
def star(self):
print("窗口开始运行")
def stop(self):
print("窗口结束运行")
def repaint(self):
print(self.msg)
MyWindow("Hello World").run()
提示:这里对文章进行总结: