How to Implement the Factory Design Pattern in Python?

80 views

How to Implement the Factory Design Pattern in Python?

How to Implement the Factory Design Pattern in Python?

What is the factory design pattern, and how can it be implemented in Python?

solveurit24@gmail.com Changed status to publish February 20, 2025
0

The factory design pattern provides an interface to create objects in a superclass, allowing subclasses to alter the type of objects that will be created. Here’s an example:

class Shape:
    def draw(self):
        pass

class Circle(Shape):
    def draw(self):
        print("Drawing a circle!")

class Square(Shape):
    def draw(self):
        print("Drawing a square!")

class ShapeFactory:
    def get_shape(self, shape_type):
        if shape_type == "circle":
            return Circle()
        elif shape_type == "square":
            return Square()
        else:
            return None

factory = ShapeFactory()
shape1 = factory.get_shape("circle")
shape1.draw()  # Output: Drawing a circle!
shape2 = factory.get_shape("square")
shape2.draw()  # Output: Drawing a square!

---

### 2. **How to Check if a String is a Palindrome Using Recursion in Python?**
**Question:** How can you check if a string is a palindrome recursively in Python?

**Answer:** A palindrome reads the same forward and backward. Here’s a recursive approach:

```python
def is_palindrome(s):
    s = s.lower().replace(" ", "")
    if len(s) <= 1:
        return True
    if s[0] != s[-1]:
        return False
    return is_palindrome(s[1:-1])

print(is_palindrome("A man a plan a canal Panama"))  # Output: True
print(is_palindrome("hello"))  # Output: False

solveurit24@gmail.com Changed status to publish February 20, 2025
0
You are viewing 1 out of 1 answers, click here to view all answers.