zoukankan      html  css  js  c++  java
  • 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("默认")
    www.wzxdm.com
  • 相关阅读:
    WCF与 Web Service的区别是什么?各自的优点在哪里呢?
    asp、asp.net、ado、ado.net各自区别和联系?
    SQL触发器 inset自学经验
    SQL触发器实例讲解
    特价汇9.9元商品
    sql中数据库连接与断开式连接有什么区别?
    终止线程的三种方法
    selenium设置代理,基于chrome浏览器
    Selenium Webdriver定位元素的几种方式
    spring常用接口 InitializingBean的作用
  • 原文地址:https://www.cnblogs.com/huxiaoyi/p/8973547.html
Copyright © 2011-2022 走看看