当前位置:网站首页 > Java教程 > 正文

java原型教程



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()

版权声明


相关文章:

  • 微信公众号 java 教程视频2024-12-12 18:50:03
  • java520教程2024-12-12 18:50:03
  • java容器教程2024-12-12 18:50:03
  • java保养教程2024-12-12 18:50:03
  • .net java教程 pdf2024-12-12 18:50:03
  • 孙鑫java web视频教程2024-12-12 18:50:03
  • 前锋Java自学教程2024-12-12 18:50:03
  • java控制翻转教程2024-12-12 18:50:03
  • bootstrap java教程2024-12-12 18:50:03
  • java指法视频教程2024-12-12 18:50:03