工厂类相关设计模式(Factory Related Pattern)

1 快餐点餐系统

在一个大的触摸显示屏上,有三类可以选择的上餐品:汉堡等主餐、小食、饮料。当我们选择好自己需要的食物,支付完成后,订单就生成了。下面,我们用今天的主角--工厂模式--来生成这些食物的逻辑主体。


In [7]:
class Burger(object):
    name=''
    price=0.0
    def getPrice(self):
        return self.price
    def setprice(self, price):
        self.price=price
    def getName(self):
        return self.name
class cheeseBurger(Burger):
    def __init__(self):
        self.name='cheese burger'
        self.price=10.0
class spicyChickenBurger(Burger):
    def __init__(self):
        self.name="spicy chicken burger"
        self.price=15.0

In [8]:
class Snack():
    name = ""
    price = 0.0
    type = "SNACK"
    def getPrice(self):
        return self.price
    def setPrice(self, price):
        self.price = price
    def getName(self):
        return self.name


class chips(Snack):
    def __init__(self):
        self.name = "chips"
        self.price = 6.0


class chickenWings(Snack):
    def __init__(self):
        self.name = "chicken wings"
        self.price = 12.0

In [9]:
class Beverage():
    name = ""
    price = 0.0
    type = "BEVERAGE"
    def getPrice(self):
        return self.price
    def setPrice(self, price):
        self.price = price
    def getName(self):
        return self.name


class coke(Beverage):
    def __init__(self):
        self.name = "coke"
        self.price = 4.0


class milk(Beverage):
    def __init__(self):
        self.name = "milk"
        self.price = 5.0

In [10]:
class foodFactory():
    type=""
    def createFood(self,foodClass):
        print (self.type," factory produce a instance.")
        foodIns=foodClass()
        return foodIns
class burgerFactory(foodFactory):
    def __init__(self):
        self.type="BURGER"
class snackFactory(foodFactory):
    def __init__(self):
        self.type="SNACK"
class beverageFactory(foodFactory):
    def __init__(self):
        self.type="BEVERAGE"

foodFactory为抽象的工厂类,而burgerFactory,snackFactory和beverageFactory则为具体的工厂类


In [11]:
burger_factory=burgerFactory()
snack_factorry=snackFactory()
beverage_factory=beverageFactory()
cheese_burger=burger_factory.createFood(cheeseBurger)
print(cheese_burger.getName(),cheese_burger.getPrice())
chicken_wings=snack_factorry.createFood(chickenWings)
print(chicken_wings.getName(),chicken_wings.getPrice())
coke_drink=beverage_factory.createFood(coke)
print (coke_drink.getName(),coke_drink.getPrice())


BURGER  factory produce a instance.
cheese burger 10.0
SNACK  factory produce a instance.
chicken wings 12.0
BEVERAGE  factory produce a instance.
coke 4.0

以上工厂在使用前必须实例化,如果为工厂添加类方法,那么就是简单工厂模式


In [16]:
class simpleFoodFactory():
    @classmethod
    def createFood(cls,foodClass):
        foodIns = foodClass()
        return foodIns

In [17]:
spicy_chickend_burger=simpleFoodFactory.createFood(spicyChickenBurger)
print(spicy_chickend_burger.getPrice())


15.0

2 Advantage

  • 封装性
  • 屏蔽产品类
  • 较高的扩展性

3 Disadvantage

  • 较为复杂
  • 产品类扩展较为复杂

In [ ]: