0
0
Software Engineeringknowledge~10 mins

Creational patterns (Singleton, Factory, Builder) in Software Engineering - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to ensure only one instance of the class is created (Singleton pattern).

Software Engineering
class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is [1]:
            cls._instance = super().__new__(cls)
        return cls._instance
Drag options to blanks, or click blank then click option'
AFalse
BNone
CTrue
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using False or 0 instead of None causes the check to fail.
2fill in blank
medium

Complete the Factory method to create a product based on the type.

Software Engineering
class Factory:
    def create_product(self, product_type):
        if product_type == 'A':
            return ProductA()
        elif product_type == 'B':
            return [1]()
        else:
            return None
Drag options to blanks, or click blank then click option'
AProductB
BProductC
CProductA
DProduct
Attempts:
3 left
💡 Hint
Common Mistakes
Returning ProductA or ProductC for product type 'B' is incorrect.
3fill in blank
hard

Fix the error in the Builder pattern's build method to return the constructed object.

Software Engineering
class Builder:
    def __init__(self):
        self.product = Product()

    def build(self):
        self.product.add_part('Part1')
        self.product.add_part('Part2')
        return [1]
Drag options to blanks, or click blank then click option'
Aself
Bproduct
Cself.product
DProduct
Attempts:
3 left
💡 Hint
Common Mistakes
Returning self or Product class instead of the product instance.
4fill in blank
hard

Fill both blanks to complete the Singleton pattern's thread-safe instance retrieval.

Software Engineering
import threading

class Singleton:
    _instance = None
    _lock = threading.Lock()

    @classmethod
    def get_instance(cls):
        with cls.[1]:
            if cls._instance is [2]:
                cls._instance = cls()
        return cls._instance
Drag options to blanks, or click blank then click option'
Alock
Bmutex
CNone
DFalse
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'mutex' instead of 'lock' or checking against False instead of None.
5fill in blank
hard

Fill all three blanks to complete a dictionary comprehension that builds a product catalog with prices above zero.

Software Engineering
products = {'apple': 1.2, 'banana': 0, 'cherry': 2.5}
catalog = [1]: [2] for [3] in products.items() if [2] > 0
Drag options to blanks, or click blank then click option'
Aname
Bprice
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up keys and values or using inconsistent variable names.