设计模式是解决软件开发中常见问题的通用解决方案。本主题文档旨在提供Python中常见设计模式的示例。

Section 167.1: 设计模式简介及单例模式

设计模式为软件设计中的常见问题提供了解决方案。设计模式最初由GoF(四人组)引入,他们将常见模式描述为反复出现的问题及其解决方案。

设计模式有四个基本要素:

  1. 模式名称:是一个我们可以在一两个词中描述设计问题、其解决方案及其后果的句柄。
  2. 问题:描述何时应用该模式。
  3. 解决方案:描述组成设计的元素、它们之间的关系、职责和协作。
  4. 后果:是应用该模式的结果和权衡。

设计模式的优点:

  1. 它们可以在多个项目中重用。
  2. 可以解决架构层面的问题。
  3. 它们经过时间检验且经过验证,是开发人员和架构师的经验。
  4. 它们具有可靠性和依赖性。

设计模式可以分为三类:

  1. 创建型模式
  2. 结构型模式
  3. 行为型模式

  4. 创建型模式:它们关注对象如何创建,并隔离对象创建的细节。

  5. 结构型模式:它们设计类和对象的结构,以便它们可以组合以实现更大的结果。
  6. 行为型模式:它们关注对象之间的交互以及对象的责任。

单例模式:

单例模式是一种创建型模式,它提供了一种机制,确保给定类型的对象只有一个,并提供全局访问点。

例如,单例模式可以用于数据库操作,我们希望数据库对象保持数据一致性。

实现

我们可以通过创建单例类的唯一实例并在后续请求中返回相同的对象来在Python中实现单例模式。

class Singleton(object):
  def __new__(cls):
    # hasattr method checks if the class object an instance property or not.
    if not hasattr(cls, 'instance'):
      cls.instance = super(Singleton, cls).__new__(cls)
      return cls.instance

s = Singleton()
print ("Object created", s)

s1 = Singleton()
print ("Object2 created", s1)

输出:

('Object created', <__main__.Singleton object at 0x10a7cc310>)
('Object2 created', <__main__.Singleton object at 0x10a7cc310>)

设计模式简介及单例模式

注意,在C++或Java等语言中,此模式通过将构造函数设为私有并创建一个静态方法来实现对象初始化。这样,第一次调用时会创建一个对象,之后类会返回同一个对象。但在Python中,我们没有创建私有构造函数的方法。

工厂模式

工厂模式也是一种创建型模式。术语“工厂”意味着一个类负责创建其他类型的对象。有一个充当工厂的类,它具有与对象和方法相关联的。客户端通过调用某些参数的方法来创建对象,工厂创建所需类型的对象并将其返回给客户端。

from abc import ABCMeta, abstractmethod

class Music():
  __metaclass__ = ABCMeta
  @abstractmethod
  def do_play(self):
    pass

class Mp3(Music):
  def do_play(self):
    print ("Playing .mp3 music!")

class Ogg(Music):
  def do_play(self):
    print ("Playing .ogg music!")

class MusicFactory(object):
  def play_sound(self, object_type):
    return eval(object_type)().do_play()

if __name__ == "__main__":
  mf = MusicFactory()
  music = input("Which music you want to play Mp3 or Ogg")
  mf.play_sound(music)

输出:

Which music you want to play Mp3 or Ogg"Ogg"
Playing .ogg music!

工厂模式

在这里,MusicFactory是工厂类,它根据用户提供的选择创建Mp3或Ogg类型的对象。

Section 167.2: 策略模式

这种设计模式称为策略模式。它用于定义一组算法,将每个算法封装起来,并使它们可以互换。策略设计模式允许算法独立于使用它的客户端而变化。

例如,动物可以以许多不同的方式“行走”。行走可以被认为是一种策略,由不同类型的动物实现:

from types import MethodType

class Animal(object):

  def __init__(self, *args, **kwargs):
    self.name = kwargs.pop('name', None) or 'Animal'
    if kwargs.get('walk', None):
      self.walk = MethodType(kwargs.pop('walk'), self)

  def walk(self):
    """
    Cause animal instance to walk

    Walking functionality is a strategy, and is intended to
    be implemented separately by different types of animals.
    """
    message = '{} should implement a walk method'.format(self.__class__.__name__)
    raise NotImplementedError(message)

# 这里是一些不同的行走算法,可以用于Animal
def snake_walk(self):
  print('I am slithering side to side because I am a {}.'.format(self.name))

def four_legged_animal_walk(self):
  print('I am using all four of my legs to walk because I am a(n) {}.'.format(self.name))

def two_legged_animal_walk(self):
  print('I am standing up on my two legs to walk because I am a {}.'.format(self.name))

运行此示例将产生以下输出:

generic_animal = Animal()
king_cobra = Animal(name='King Cobra', walk=snake_walk)
elephant = Animal(name='Elephant', walk=four_legged_animal_walk)
kangaroo = Animal(name='Kangaroo', walk=two_legged_animal_walk)

kangaroo.walk()
elephant.walk()
king_cobra.walk()
# 这一个将引发NotImplementedError,以通知程序员
# walk方法旨在用作策略。
generic_animal.walk()
  # OUTPUT:
  #
  # I am standing up on my two legs to walk because I am a Kangaroo.
  # I am using all four of my legs to walk because I am a(n) Elephant.
  # I am slithering side to side because I am a King Cobra.
  # Traceback (most recent call last):
  # File "./strategy.py", line 56, in <module>
  # generic_animal.walk()
  # File "./strategy.py", line 30, in walk
  # raise NotImplementedError(message)
  # NotImplementedError: Animal should implement a walk method

策略模式

注意,在C++或Java等语言中,此模式通过使用抽象类或接口定义策略来实现。在Python中,更有意义的是使用types.MethodType动态地将一些函数添加到类中。

Section 167.3: 代理模式

代理对象通常用于确保对另一个对象的安全访问,我们不想用安全要求污染其内部业务逻辑。

假设我们希望保证只有具有特定权限的用户才能访问资源。

代理定义:(它确保只有真正能够查看预订的用户才能使用预订服务)

from datetime import date
from operator import attrgetter

class Proxy:
  def __init__(self, current_user, reservation_service):
    self.current_user = current_user
    self.reservation_service = reservation_service

  def highest_total_price_reservations(self, date_from, date_to, reservations_count):
    if self.current_user.can_see_reservations:
      return self.reservation_service.highest_total_price_reservations(
        date_from,
        date_to,
        reservations_count
      )
    else:
      return []

# 模型和预订服务:
class Reservation:
  def __init__(self, date, total_price):
    self.date = date
    self.total_price = total_price

class ReservationService:
  def highest_total_price_reservations(self, date_from, date_to, reservations_count):
    # 通常会从数据库/外部服务中读取
    reservations = [
      Reservation(date(2014, 5, 15), 100),
      Reservation(date(2017, 5, 15), 10),
      Reservation(date(2017, 1, 15), 50)
    ]

    filtered_reservations = [r for r in reservations if (date_from <= r.date <= date_to)]
    sorted_reservations = sorted(filtered_reservations, 
                                 key=attrgetter('total_price'),reverse=True)
    return sorted_reservations[0:reservations_count]

class User:
  def __init__(self, can_see_reservations, name):
    self.can_see_reservations = can_see_reservations
    self.name = name

# 消费服务:
class StatsService:
  def __init__(self, reservation_service):
    self.reservation_service = reservation_service

  def year_top_100_reservations_average_total_price(self, year):
    reservations = self.reservation_service.highest_total_price_reservations(
      date(year, 1, 1),
      date(year, 12, 31),
      1
    )

    if len(reservations) > 0:
      total = sum(r.total_price for r in reservations)
      return total / len(reservations)
    else:
      return 0

# 测试:
def test(user, year):
  reservations_service = Proxy(user, ReservationService())
  stats_service = StatsService(reservations_service)
  average_price = stats_service.year_top_100_reservations_average_total_price(year)
  print("{0} will see: {1}".format(user.name, average_price))

test(User(True, "John the Admin"), 2017)
test(User(False, "Guest"), 2017)

代理模式

优点:

  • 当访问限制发生变化时,我们避免了对ReservationService的任何更改。
  • 我们没有将与领域无关的概念(用户权限)与业务相关数据(date_from、date_to、reservations_count)混合在服务中。
  • 消费者(StatsService)也免于与权限相关的逻辑。

注意事项:

代理接口总是与它隐藏的对象完全相同,这样使用代理包装的服务的用户甚至没有意识到代理的存在。