Builder和Factory设计模式理解

What is the difference between Builder Design pattern and Factory Design pattern? - Stack Overflow

A factory is simply a wrapper function around a constructor (possibly one in a different class). The key difference is that a factory method pattern requires the entire object to be built in a single method call, with all the parameters passed in on a single line. The final object will be returned.

A builder pattern, on the other hand, is in essence a wrapper object around all the possible parameters you might want to pass into a constructor invocation. This allows you to use setter methods to slowly build up your parameter list. One additional method on a builder class is a build() method, which simply passes the builder object into the desired constructor, and returns the result.

In static languages like Java, this becomes more important when you have more than a handful of (potentially optional) parameters, as it avoids the requirement to have telescopic constructors for all the possible combinations of parameters. Also a builder allows you to use setter methods to define read-only or private fields that cannot be directly modified after the constructor has been called.

上述为Stackoverflow的回答。

简单来说就是:

factory模式就是在你定义了一个class A之后,再定义一个AFactory类,来单独存放A class的各种构造函数。AFactory的每一个函数都会返回A的一个对象。

factory模式在java中较为常见,在python,go,C++中几乎不会见到,因为java在new一个对象时只能使用class的同名构造函数,只能用过参数个数来区分不同的同名构造函数。而其他语言大多支持自定义名称的构造函数因此无需额外的Factory类。

以python为例,我们看下两者的区别:

# coding=utf-8
# @Time: 2022/1/10 17:59
from typing import List


class A(object):
    def __init__(self, name: str):
        self.__name = name

    @classmethod
    def NewAFromList(cls, strs: List[str]):
        AList = []
        for s in strs:
            cls_kwargs = {"name": s}
            AList.append(cls(**cls_kwargs))
        return AList

    def __repr__(self):
        return self.__name


class AFactory(object):
    @staticmethod
    def NewAFromList(strs: List[str]) -> List[A]:
        AList = []
        for s in strs:
            AList.append(A(name=s))
        return AList


if __name__ == '__main__':
    # As = A.NewAFromList(["a", "b"])
    # for e in As:
    #     print(e)

    Af = AFactory()
    As = Af.NewAFromList(strs=["a", "b"])
    for e in As:
        print(e)

上述python的demo中,直接使用A的构造函数NewAFromList就很方便了,虽然额外加一个AFactory也能实现需求,但明显是多此一举。就算A有几十种构造函数也没什么必要单独拉一个Factory类出来。factory模式中每一个Factory的函数都相当于原始类的一个构造函数,它会直接返回要构造的原始对象,但builder模式不同,它构建最终返回对象的步骤是一步一步来的,每一步都会返回builder类本身,相当于每一步返回一个半成品(即构造原始对象的一个组件),直到最后的build()函数才会返回最终对象,返回的最终对象具体包含什么组件,取决于你调用了构造类的哪些函数。builder模式的作用与factory的区别这里就体现出来了,builder模式在java以外的其他语言中也有其使用价值,可以用于构造复杂的可变对象。直接上一个demo最好:

# coding=utf-8
# @Time: 2022/1/10 17:59


class A(object):
    def __init__(self, name: str, gender: str = None, age: int = None):
        self.__name = name
        self.__gender = gender
        self.__age = age

    def setName(self, name: str):
        self.__name = name

    def setGender(self, gender: str):
        self.__gender = gender

    def setAge(self, age: int):
        self.__age = age

    def info(self):
        print("Name: %s, Gender: %s, Age: %s" % (self.__name,
                                                 self.__gender if self.__gender else "Unknown",
                                                 self.__age if self.__age else "Unknown"))


class ABuilder(object):
    def __init__(self):
        self.__A = A(name=None)

    def addName(self, name: str):
        self.__A.setName(name)
        return self

    def addGender(self, gender: str):
        self.__A.setGender(gender)
        return self

    def addAge(self, age: str):
        self.__A.setAge(age)
        return self

    def build(self) -> A:
        return self.__A


if __name__ == '__main__':
    chen = ABuilder().addName("chen").addAge(10).build()
    iuna = ABuilder().addName("iuna").build()
    chen.info()
    iuna.info()

 

  

 

posted @ 2022-02-10 12:35  realcp1018  阅读(415)  评论(0编辑  收藏  举报