Answer the question
In order to leave comments, you need to log in
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)
Answer the question
In order to leave comments, you need to log in
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)
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 questionAsk a Question
731 491 924 answers to any question