ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

设计模式之抽象工厂模式

2022-07-27 11:35:42  阅读:138  来源: 互联网

标签:return color self 工厂 抽象 print 设计模式 class def


 抽象工厂模式

  抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

  在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。

  意图:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

  

  

 

  实现如下:

    

# -*- coding:utf-8 -*-
__author__ = "xiaomagua"


class AbstractFactory:
    def get_shape():
        pass
    def get_color():
        pass


class Shape(object):
    def draw(self):
        print("draw noting...")

class Circle(Shape):
    def draw(self):
        print("draw circle...")

class Rectangle(Shape):
    def draw(self):
        print("draw rectangle...")


class ShapeFactory(AbstractFactory):
    def get_shape(self, shape):
        if shape == "Circle":
            return Circle()
        elif shape == "Rectangle":
            return Rectangle()
        else:
            print("illegal parameter...")
            return None

class Color(object):
    def fill(self):
        print("fill noting...")

class Red(Color):
    def fill(self):
        print("fill red...")

class Green(Shape):
    def fill(self):
        print("fill green...")


class ColorFactory(AbstractFactory):
    def get_color(self, color):
        if color == "Red":
            return Red()
        elif color == "Green":
            return Green()
        else:
            print("illegal parameter...")
            return None


class FactoryProducer:
    def get_factory(self, choice) -> AbstractFactory: 
        if choice not in ["shape", "color"]:
            return None
        else:
            if choice == "shape":
                return ShapeFactory()
            if choice == "color":
                return ColorFactory()

color_factory = FactoryProducer().get_factory("color")
green = color_factory.get_color("Green")
green.fill()

 

标签:return,color,self,工厂,抽象,print,设计模式,class,def
来源: https://www.cnblogs.com/xiaomagua/p/16524248.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有