Z
Z
zlodiak2019-04-30 23:26:08
Python
zlodiak, 2019-04-30 23:26:08

Does factory method conflict with OCP?

Please tell me, do I understand correctly that solid principles are not a recipe for all cases? And quite a common occurrence is the deliberate violation of some solid principles. For example, there is a factory method
pattern . Here is its implementation:

class Door:
    def __init__(self, weight):
        self.weight = weight

    def __str__(self):
        return str(self.weight)

class Brick:
    def __init__(self, weight):
        self.weight = weight

    def __str__(self):
        return str(self.weight)        

class FactoryMethod:
    def create(self, weight, type_):
        pass

class Creator(FactoryMethod):
    def create(self, type_, weight):
        if type_ == 'door':
            print('door with weight: ', Door(weight))
        else:
            print('brick with weight: ', Brick(weight))

c = Creator()
c.create('brick', 10)
c.create('door', 100)

As you can see, it violates one of the solid principles, namely the principle of openness / closeness. If you need to generate windows in addition to doors and bricks, then you will have to make changes to the Creator.create () method.
And the open / closed principle prohibits changing the code written earlier, it only allows you to add a new one.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MechanicZelenyy, 2019-04-30
@MechanicZelenyy

What you brought is not a factory method. And the factory design pattern.
A factory method is a static (classmethod in Python) that returns an instance of a class.
Example:

class Door:
    def __init__(self, weight):
        self.weight = weight

    def __str__(self):
        return str(self.weight)

# фабричный метод
    def door_from_window(cls, window):
        # какой-то код

door = Door.door_from_windwow(window)

E
Evgeny Romashkan, 2019-05-01
@EvgeniiR

The factory method returns objects of the same type, this is even shown in the article you cited.
That is, for good, all that the client code should know when calling a factory method is an object with which interface / instance of which abstract class should be returned.
By the way, advice, beginners often sin with this - do not try to cram patterns into the code, just for what they are, and do not try to learn them to improve the quality of your code. These are rather the names of the most frequently repeated places in different programs.
If the patterns are interesting and you want to benefit from it - try to find more examples of the use of the currently studied ones, and understand why they were chosen. There will be space to think

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question