设计模式之抽象工厂模式

 抽象工厂模式

  抽象工厂模式(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()

 

posted @ 2022-07-27 11:29  一只小麻瓜  阅读(15)  评论(0编辑  收藏  举报