设计模式----抽象工厂模式
Posted 幻觉czw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式----抽象工厂模式相关的知识,希望对你有一定的参考价值。
<pre name="code" class="python">#武器工厂
#抽象工厂模式
'''抽象工厂模式是所有形态的工厂模式中最为抽象和最具一般性的一种形态。抽象工厂模式是指当有多个抽象角色时,使用的一种工厂模式。抽象工厂模式可以向客户端提供一个接口,使客户端在不必指定产品的具体的情况下,创建多个产品族中的产品对象。根据LSP原则,任何接受父类型的地方,都应当能够接受子类型。因此,实际上系统所需要的,仅仅是类型与这些抽象产品角色相同的一些实例,而不是这些抽象产品的实例。换言之,也就是这些抽象产品的具体子类的实例。工厂类负责创建抽象产品的具体子类的实例。'''
'''武器工厂生产武器的实例,不同属性的工厂生产不同属性的武器,武器的攻击可
以设定,工厂需添加相应武器的类才能生产实例'''
class WeaponFactory(object):
'''This is an abstract class WeaponFactory'''
def __init__(self,weapon = None):
self.weapons = weapon.__name__ : weapon
def createweapon(self,name,attack):
pass
def addweapon(self,weapon):
if self.weapons.has_key(weapon.__name__):
raise KeyError("we have had this weapon")
self.weapons[weapon.__name__] = weapon
def removeweapon(self,name):
if not self.weapons.has_key(name):
raise KeyError("we don't have this weapon")
self.weapons.pop(name)
class FireWeaponFactory(WeaponFactory):
'''This is a concreate class FireWeaponFactory'''
def __init__(self,weapon = None):
self.position = 'Fire'
WeaponFactory.__init__(self,weapon)
def createweapon(self,name,attack = 0):
if not self.weapons.has_key(name):
raise KeyError("we don't have this weapon")
return self.weapons[name](attack,self.position)
class WaterWeaponFactory(WeaponFactory):
'''This is a concreate class WaterWeaponFactory'''
def __init__(self,weapon = None):
self.position = 'Water'
WeaponFactory.__init__(self,weapon)
def createweapon(self,name,attack):
if not self.weapons.has_key(name):
raise KeyError("we don't have this weapon")
return self.weapons[name](attack,self.position)
class Weapon(object):
'''This is an abstract class Weapon'''
def __init__(self,attack = 0,position = None):
self._attack = attack
self._position = position
@property
def attack(self):
return self._attack
@attack.setter
def attack(self,value):
raise ValueError("you can't set attack")
@attack.deleter
def attack(self):
raise AttributeError("you can't delete attack")
@property
def position(self):
return self._position
@position.setter
def position(self,value):
raise ValueError("you can't set position")
@position.deleter
def position(self):
raise AttributeError("you can't delete position")
class Bow(Weapon):
'''a class Bow'''
def __str__(self):
return Bow.__name__
class Sword(Weapon):
'''a class Sword'''
def __str__(self):
return Sword.__name__
class Gun(Weapon):
'''a class Gun'''
def __str__(self):
return Gun.__name__
if __name__ == '__main__':
mf = FireWeaponFactory(Bow)
mbow = mf.createweapon('Bow',120)
mf.addweapon(Sword)
msword = mf.createweapon('Sword',170)
mw = WaterWeaponFactory(Bow)
ybow = mw.createweapon('Bow',190)
#mf.removeweapon('Sword')
print mbow.attack
print mbow.position
print '--'*30
print msword.attack
print msword.position
print '--'*30
print ybow.attack
print ybow.position
print '--'*30
print mf.createweapon('Sword',210)
以上是关于设计模式----抽象工厂模式的主要内容,如果未能解决你的问题,请参考以下文章