Python 方式:
# 原型模式 with Python
import copy
# 用copy包实现深拷贝(copy.deepcopy())和浅拷贝(copy.copy())
from abc import abstractmethod,ABCMeta
# 创建一接口
class Shape(metaclass=ABCMeta):
_id =""
in_type = ""
@abstractmethod
def draw(self):
pass
def getType(self):
return self.in_type
def getID(self):
return self._id
def setID(self,in_id):
self._id = in_id
def clone(self):
#深拷贝
myclone = copy.deepcopy(self)
return myclone
# 创建实体类
class Rectangle(Shape):
def __init__(self):
self.in_type = "Rectangel"
def draw(self):
print("Inside Rectangle.draw() method.")
class Square(Shape):
def __init__(self):
self.in_type = "Square"
def draw(self):
print("Inside Square.draw() method.")
class Circle(Shape):
def __init__(self):
self.in_type = "Circle"
def draw(self):
print("Inside Circle.draw() method.")
# 获取数据实体类
class ShapeCache():
#Python 无静态变量,用开放类变量
shapeMap = {}
def getShape(self,shapeID):
cachedShape = self.shapeMap[shapeID]
return cachedShape.clone()
# 静态方法
@staticmethod
def loadCache():
circle1 = Circle()
circle1.setID("1")
ShapeCache.shapeMap[circle1.getID()] = circle1
square1 = Square()
square1.setID("2")
ShapeCache.shapeMap[square1.getID()] = square1
rectangle1 = Rectangle()
rectangle1.setID("3")
ShapeCache.shapeMap[rectangle1.getID()] = rectangle1
# 调用输出
if __name__ == '__main__':
ShapeCache.loadCache()
myShape = ShapeCache()
cloneShape1 = myShape.getShape("1")
print("Shape : %s" %cloneShape1.getType())
cloneShape1.draw()
cloneShape2 = myShape.getShape("2")
print("Shape : %s" % cloneShape2.getType())
cloneShape2.draw()
cloneShape3 = myShape.getShape("3")
print("Shape : %s" % cloneShape3.getType())
cloneShape3.draw()
Siskin.xu
Siskin.xu
sis***@sohu.com12个月前 (02-28)