How to access model class in View using Controller

6 views (last 30 days)
Programmatic GUI
i want to access model by controlller only but not by notity or events.
and without any relation between view and model
simpy this structure.

Answers (1)

Pratyush
Pratyush on 22 Dec 2023
Hi Deepak,
I understand that you want to implement a Model-Controller pattern where the controller has access to the model but there is no direct communication between the view and the model (i.e., no use of notifications or events), you can design your system in a way that the view only communicates with the controller, and the controller handles all interactions with the model.
Here's a simplified outline of how you might structure your code:
  • The model contains the data and the logic of your application. It does not know about the controller or the view.
classdef Model
properties
Data
end
methods
function obj = Model(data)
obj.Data = data;
end
function data = getData(obj)
data = obj.Data;
end
function obj = setData(obj, newData)
obj.Data = newData;
end
% Other methods to manipulate the data
end
end
  • The controller has access to the model and can retrieve or update data. The controller also processes user input from the view and updates the view accordingly.
classdef Controller
properties
Model
View
end
methods
function obj = Controller(model, view)
obj.Model = model;
obj.View = view;
% Set the controller as a property in the view
obj.View.Controller = obj;
end
function updateModel(obj, newData)
obj.Model.setData(newData);
% Optionally update the view after changing the model
obj.updateView();
end
function updateView(obj)
% Fetch data from the model
data = obj.Model.getData();
% Update the view with new data
obj.View.displayData(data);
end
% Other methods to handle user actions
end
end
  • The view is responsible for displaying the data. It receives user input and notifies the controller but does not interact with the model directly.
classdef View
properties
Controller
end
methods
function obj = View()
% View initialization code here
end
function displayData(obj, data)
% Code to display data in the view
disp(data);
end
function userAction(obj, newData)
% This method is called when the user performs an action
% that should update the model.
obj.Controller.updateModel(newData);
end
% Other methods related to the user interface
end
end
  • You can tie these components together as follows:
% Create the model with initial data
model = Model(initialData);
% Create the view
view = View();
% Create the controller with references to both the model and the view
controller = Controller(model, view);
% Now you can use the controller to manipulate the model
controller.updateModel(newData);
% And the view to display data
view.displayData(controller.Model.getData());
Hope this helps.

Tags

Products


Release

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!