简体   繁体   中英

benefits of the Factory Pattern?

I have programmed the following Factory pattern according to a Design Patterns book:

class Pizza():
    def __init__(self):
        self. cost=0

    @property
    def cost(self):
        return self.cost

class PizzaFactory():

   class Clamp(Pizza):
    def __init__(self):
        self.cost=10

   class Vegan(Pizza):
     def __init__(self):
        self.preci0=40

   class NY(Pizza):
     def __init__(self):
         self.cost=30

   @staticmethod
   def makePizza(type):
        if type=="Clamp":
            return Clamp()
        elif type=="Vegan":
            return Vegan()
        elif type=="NY":
            return NY()

def main():
    PizzaFactory=PizzaFactory()
    print PizzaFactory.makePizza("Clamp").cost

if __name__=="__main__":
    main()

I got the point that is for centralizing the constructors, and that in Java is used for not using the new word all the time, but I am not quite sure if it has a straight use in Python.

Almost all the examples I found they do the same, put some simple creation of objects inside one Factory class and said that it will extend my class more easily, but I do not see a concrete example.

Could somebody give me an example that could prove this Factory pattern to be useful for the programmed example I made?

Thanks

PD. By the way I found that the Factory Pattern it is built in Python, so it gives the impression that Python lack of some patterns. Source: http://cdn.oreillystatic.com/en/assets/1/event/12/ The%20Lack%20of %20Design%20Patterns%20in%20Python%20Presentation.pdf

Your example is very simple and probably won't have any "real" use cases.

Here is a factory function I've written. It figures out which class to use based on a string identifier. These identifiers are loaded dynamically at runtime from JSON that looks like this . The dynamic nature of the factory makes these classes more extensible, since anyone can hook this factory and add more classes to the system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM