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
  • 相关阅读:
    kubernetes 笔记 1
    Linux 性能优化笔记 --CPU总结
    Linux 性能优化笔记 --CPU
    RedHat OpenShift QuickStart 2.4 容器主机
    docker 常用命令
    RedHat OpenShift QuickStart 2.3 容器注册
    SpringBoot自动配置源码
    RedHat OpenShift QuickStart 2.2 容器镜像
    RedHat OpenShift QuickStart 2.1 容器介绍
    RedHat OpenShift QuickStart 1.2 容器中传入/出文件
  • 原文地址:https://www.cnblogs.com/huxiaoyi/p/8973547.html
Copyright © 2011-2022 走看看