search
HomeBackend DevelopmentPython Tutorial举例讲解Python设计模式编程的代理模式与抽象工厂模式

代理模式
Proxy模式是一种常用的设计模式,它主要用来通过一个对象(比如B)给一个对象(比如A) 提供'代理'的方式方式访问。比如一个对象不方便直接引用,代理就在这个对象和访问者之间做了中介

你先设想:一个对象提供rgb三种颜色值,我想获得一个对象的rgb三种颜色,但是我不想让你获得蓝色属性,怎么办?

class Proxy(object):
  def __init__(self, subject):
    self.__subject = subject
  # 代理其实本质上就是属性的委托
  def __getattr__(self, name):
    return getattr(self.__subject, name)

class RGB:
  def __init__(self, red, green, blue):
    self.__red = red
    self.__green = green
    self.__blue = blue
  def Red(self):
    return self.__red
  def Green(self):
    return self.__green
  def Blue(self):
    return self.__blue

class NoBlueProxy(Proxy):
  # 我在这个子代理类拦截了blue的访问,这样就不会返回被代理的类的Blue属性
  def Blue(self):
    return 0

if __name__ == '__main__':
  rgb = RGB(100, 192, 240)
  print rgb.Red()
  proxy = Proxy(rgb)
  print proxy.Green()
  noblue = NoBlueProxy(rgb)
  print noblue.Green()
  print noblue.Blue()

抽象工厂模式
和简单工厂/工厂方法不同,抽象工厂可能最好理解,举个例子:
比如2个动物,猫和狗,他们都有speak和eat的function,但是很明显他们执行的结果是不同的 有个'工厂'(抽象工厂里面一个类型就是一个工厂,这点和其他模式的不同)专门帮助我们找到对应的动物做正确的操作 有个类/函数可以通过参数帮助我们找到上面的这个工厂  这就是抽象工厂

from abc import ABCMeta

class StandardFactory(object):
  '''这就是那个抽象工厂'''
  @staticmethod
  def get_factory(factory):
    '''根据参数找到对实际操作的工厂'''
    if factory == 'cat':
      return CatFactory()
    elif factory == 'dog':
      return DogFactory()
    raise TypeError('Unknown Factory.')


这里帮助dog这个产品类找到应该的属性的工厂
class DogFactory(object):
  def get_pet(self):
    return Dog();


class CatFactory(object):
  # 注意这个方法和上面的名字一样,但是返回的类不同,这就是工厂的作用
  def get_pet(self):
    return Cat();


# 可以认为dog和cat都是动物的一种,可以有个基类
class Pet(object):
  # ABCMeta会让这个类在注册后添加很多基础抽象基类,可以看[ABCMeta](http://docs.python.org/2/library/abc.html#abc.ABCMeta)
  __metaclass__ = ABCMeta
  def eat(self):
    pass


# Dog应该做什么就是这里
class Dog(Pet):
  def eat(self):
    return 'Dog food...'


class Cat(Pet):
  # 这里的eat依然是同名,她们都是同样的操作,只是返回不同
  def eat(self):
    return 'Cat food...'


if __name__ =="__main__":
  factory = StandardFactory.get_factory('cat')
  pet = factory.get_pet()
  print pet.eat()

  # 注意这里,你只需要修改抽象工厂传入的那个参数,其他什么都不用改
  factory = StandardFactory.get_factory('dog')
  pet = factory.get_pet()
  print pet.eat()

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

What is a lambda function?What is a lambda function?Apr 28, 2025 pm 04:28 PM

Article discusses lambda functions, their differences from regular functions, and their utility in programming scenarios. Not all languages support them.

What is a break, continue and pass in Python?What is a break, continue and pass in Python?Apr 28, 2025 pm 04:26 PM

Article discusses break, continue, and pass in Python, explaining their roles in controlling loop execution and program flow.

What is a pass in Python?What is a pass in Python?Apr 28, 2025 pm 04:25 PM

The article discusses the 'pass' statement in Python, a null operation used as a placeholder in code structures like functions and classes, allowing for future implementation without syntax errors.

Can we Pass a function as an argument in Python?Can we Pass a function as an argument in Python?Apr 28, 2025 pm 04:23 PM

Article discusses passing functions as arguments in Python, highlighting benefits like modularity and use cases such as sorting and decorators.

What is the difference between / and // in Python?What is the difference between / and // in Python?Apr 28, 2025 pm 04:21 PM

Article discusses / and // operators in Python: / for true division, // for floor division. Main issue is understanding their differences and use cases.Character count: 158

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),