Python类设计模式——简单工厂模式

在设计一个类的过程当中,如果需要多个类,那么一次一次定义类显得纷繁复杂,就引入了设计模式这个概念,工厂模式就是其中的一种,以蛋糕店为例,按味道区分的话,蛋糕的种类是多种多样的,见代码:

#coding=utf-8
class Cake(object):
    def __init__(self,taste="默认"):
        self.taste = taste
class AppleCake(object):
    def __init__(self,taste="苹果味"):
        self.taste = taste
class BananaCake(object):
    def __init__(self,taste="香蕉味"):
        self.taste = taste

class CakeStore(object):
    def taste(self,taste):
        if taste == "苹果":
            cake= AppleCake()
        if taste == "香蕉":
            cake = BananaCake()
        print("-----味道:%s-----"%cake.taste)

a = CakeStore()
a.taste("苹果")

工厂模式的思路是,我可不可以不要总是定义类,不要每次都写那么多代码,就可以上新产品呢?解决的办法是:

#coding=utf-8
class Cake(object):
    def __init__(self,taste="默认"):
        self.taste = taste
class AppleCake(object):
    def __init__(self,taste="苹果味"):
        self.taste = taste
class BananaCake(object):
    def __init__(self,taste="香蕉味"):
        self.taste = taste
class CakeKitchen(object):
    def createCake(self, taste):
        if taste == "苹果":
            cake= AppleCake()
        elif taste == "香蕉":
            cake = BananaCake()
        elif taste == "默认":
            cake  = Cake()
        return cake
class CakeStore(object):
    def __init__(self):
        self.kitchen = CakeKitchen()
    def taste(self,taste):
        cake = self.kitchen.createCake(taste)
        print("-----味道:%s-----"%cake.taste)

a = CakeStore()
a.taste("苹果")
a.taste("香蕉")
a.taste("默认")