Copyright © 2022-2025 aizws.net · 网站版本: v1.2.6·内部版本: v1.25.2·
页面加载耗时 0.00 毫秒·物理内存 156.0MB ·虚拟内存 1438.1MB
欢迎来到 AI 中文社区(简称 AI 中文社),这里是学习交流 AI 人工智能技术的中文社区。 为了更好的体验,本站推荐使用 Chrome 浏览器。
原型设计模式有助于隐藏类创建的实例的复杂性。现有对象的概念与从头创建的新对象的概念不同。
如果需要,新复制的对象的属性可能会有一些更改。这种方法可以节省开发产品所需的时间和资源。
现在让我们看看如何实现原型模式。
# Filename : example.py
# Date : 2020-08-22
import copy
class Prototype:
_type = None
_value = None
def clone(self):
pass
def getType(self):
return self._type
def getValue(self):
return self._value
class Type1(Prototype):
def __init__(self, number):
self._type = "Type1"
self._value = number
def clone(self):
return copy.copy(self)
class Type2(Prototype):
""" Concrete prototype. """
def __init__(self, number):
self._type = "Type2"
self._value = number
def clone(self):
return copy.copy(self)
class ObjectFactory:
""" Manages prototypes.
Static factory, that encapsulates prototype
initialization and then allows instatiation
of the classes from these prototypes.
"""
__type1Value1 = None
__type1Value2 = None
__type2Value1 = None
__type2Value2 = None
@staticmethod
def initialize():
ObjectFactory.__type1Value1 = Type1(1)
ObjectFactory.__type1Value2 = Type1(2)
ObjectFactory.__type2Value1 = Type2(1)
ObjectFactory.__type2Value2 = Type2(2)
@staticmethod
def getType1Value1():
return ObjectFactory.__type1Value1.clone()
@staticmethod
def getType1Value2():
return ObjectFactory.__type1Value2.clone()
@staticmethod
def getType2Value1():
return ObjectFactory.__type2Value1.clone()
@staticmethod
def getType2Value2():
return ObjectFactory.__type2Value2.clone()
def main():
ObjectFactory.initialize()
instance = ObjectFactory.getType1Value1()
print("%s: %s" % (instance.getType(), instance.getValue()))
instance = ObjectFactory.getType1Value2()
print("%s: %s" % (instance.getType(), instance.getValue()))
instance = ObjectFactory.getType2Value1()
print("%s: %s" % (instance.getType(), instance.getValue()))
instance = ObjectFactory.getType2Value2()
print("%s: %s" % (instance.getType(), instance.getValue()))
if __name__ == "__main__":
main()
上面的程序将产生以下输出-
Type1: 1 Type1: 2 Type2: 1 Type2: 2
输出有助于使用现有对象创建新对象,并且在上述输出中清晰可见。
外观模式模式为子系统中的一组接口提供了统一的接口。它定义了任何子系统都可以使用的高级接口。Facade类知道哪个子系统负责请求。 1. 如何设计外观模式?现在让我们看看如何设计外观模式。# Filename ...