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

Siskin.xu

Siskin.xu

sis***@sohu.com12个月前 (02-28)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值