Design pattern

Design pattern

Design patterns typically describe the relationships and interactions between classes or objects, emphasizing the best practices and principles that should guide their implementation. They help in promoting code reusability, maintainability, scalability, and flexibility while also improving the overall structure and organization of software systems.

There are various types of design patterns, including:

  1. Creational Patterns: These patterns focus on object creation mechanisms, providing flexibility and decoupling the system from the specific classes it needs to instantiate.
  2. Structural Patterns: Structural patterns deal with the composition of classes or objects to form larger structures, emphasizing how classes and objects can be combined to form new structures.
  3. Behavioral Patterns: Behavioral patterns focus on the communication and interaction between objects, defining the responsibilities and collaboration among them.

Today I am going to explain about one of the behavioral design pattern "Template Method design pattern" in python which is quite popular.

Template Method design pattern

The Template Method design pattern is akin(similar) to constructing a blueprint for an algorithm, where the basic structure is laid out in a base class, and specific details are filled in by subclasses. It acts as a guiding framework, allowing developers to define a series of steps to accomplish a task while permitting variations in certain steps as needed.

Main components:

Template Method Design

  1. Abstract Class (or Interface): This is the base class that defines the template method, which is the skeleton of the algorithm. The abstract class may also contain one or more abstract methods that need to be implemented by concrete subclasses. In some variations, an interface may be used instead of an abstract class.
  2. Concrete Class: Concrete classes are subclasses of the abstract class that provide implementations for the abstract methods defined in the superclass. They also override any hook methods if necessary. These classes represent specific variations of the algorithm but adhere to the overall structure defined in the template method.
  3. Template Method: This is the method defined in the abstract class that outlines the algorithm's structure. It calls various steps or methods, some of which may be abstract and implemented by subclasses, while others may be concrete and provided by the superclass.
  4. Abstract Methods (Optional): These are methods declared in the abstract class but without any implementation. Concrete subclasses must provide implementations for these methods to define specific behavior.
  5. Hook Methods (Optional): Hook methods are additional methods defined in the abstract class that provide default behavior but can be overridden by subclasses if necessary. These methods allow subclasses to influence or extend certain parts of the algorithm without changing its overall structure.


Let's delve deeper into the Template Method pattern through a comprehensive example.


Imagine you're a game developer tasked with structuring character creation for your game. Within this system, you have various character classes such as warriors, mages, and archers, each possessing their own distinct abilities. In this scenario, the most suitable design pattern is the Template Method pattern. This pattern establishes a consistent framework for character creation, enabling subclasses to implement specific abilities unique to each character class. With the Template Method pattern, you can ensure a standardized approach to character creation while accommodating the individual nuances and skills of each character type.

Here's the implementation of the character creation scenario using the Template Method pattern in Python:

from abc import ABC, abstractmethod

class CharacterCreator(ABC):
    def create_character(self):
        self.choose_class()
        self.set_stats()
        self.choose_ability()
        self.display_character_info()

    @abstractmethod
    def choose_class(self):
        pass

    @abstractmethod
    def set_stats(self):
        pass

    @abstractmethod
    def choose_ability(self):
        pass

    def display_character_info(self):
        print("Character info:")
        print(f"Class: {self.character_class}")
        print(f"Stats: {self.stats}")
        print(f"Ability: {self.ability}")

class Warrior(CharacterCreator):
    def choose_class(self):
        self.character_class = "Warrior"

    def set_stats(self):
        self.stats = {"Strength": 10, "Agility": 5, "Intelligence": 3}

    def choose_ability(self):
        self.ability = "Sword Slash"

class Mage(CharacterCreator):
    def choose_class(self):
        self.character_class = "Mage"

    def set_stats(self):
        self.stats = {"Strength": 3, "Agility": 5, "Intelligence": 10}

    def choose_ability(self):
        self.ability = "Fireball"

class Archer(CharacterCreator):
    def choose_class(self):
        self.character_class = "Archer"

    def set_stats(self):
        self.stats = {"Strength": 5, "Agility": 10, "Intelligence": 5}

    def choose_ability(self):
        self.ability = "Arrow Rain"

# Usage
if __name__ == "__main__":
    warrior = Warrior()
    warrior.create_character()

    mage = Mage()
    mage.create_character()

    archer = Archer()
    archer.create_character()
        

In this code:

  • CharacterCreator is the abstract superclass defining the template method create_character(), which handles the common steps for character creation: choosing a class, setting stats, choosing an ability, and displaying character information.
  • Subclasses Warrior, Mage, and Archer override the abstract methods to implement class-specific behavior for choosing a class, setting stats, and choosing an ability.
  • When you run the code, it creates instances of each character class and calls the create_character() method, which executes the template method, resulting in the creation of characters with their respective attributes.


Now, let's discuss the pros and cons of using the Template Method pattern:

Pros:

  • Supports Open/Closed Principle:
  • Encourages Consistency
  • Provides Abstraction

Cons:

  • Limited Flexibility
  • Potential for Tight Coupling
  • Difficulties in Understanding


Conclusion:

In conclusion, the Template Method design pattern serves as a cornerstone in software architecture, empowering developers to build robust, scalable, and maintainable solutions. By encapsulating algorithmic structure and promoting customization, the Template Method pattern facilitates code reuse, flexibility, and adaptability across diverse software development scenarios.

要查看或添加评论,请登录

Er. Jiwan Gharti的更多文章

  • Creational Design Pattern

    Creational Design Pattern

    Creational design patterns are like toolkits for creating objects efficiently, enabling flexibility and reusability in…

  • Design Pattern:

    Design Pattern:

    In the realm of software development, the design phase plays a crucial role in laying the foundation for a successful…

社区洞察

其他会员也浏览了