Sobes.tech
Junior — Middle

Can you give an example of a design pattern that separates responsibilities between components?

sobes.tech AI

Answer from AI

One of the classic design patterns that separates responsibilities between components is Model-View-Controller (MVC).

  • Model is responsible for data and business logic.
  • View is responsible for displaying information to the user.
  • Controller connects the Model and View, handles user input, and updates the View.

An example in C# (simplified):

// Model
class User {
    public string Name { get; set; }
}

// View
class UserView {
    public void DisplayUser(string userName) {
        Console.WriteLine("User: " + userName);
    }
}

// Controller
class UserController {
    private User model;
    private UserView view;

    public UserController(User model, UserView view) {
        this.model = model;
        this.view = view;
    }

    public void SetUserName(string name) {
        model.Name = name;
    }

    public void UpdateView() {
        view.DisplayUser(model.Name);
    }
}

This approach helps to separate responsibilities and makes the code easier to maintain and test.