How to communicate among objects from different classes in a solid way?
이전 댓글 표시
Hi all,
This is a really long question, thanks for your patience!
Imagine I have two classes like this:
classdef beam < handle
properties
stiff_mtx1
stiff_mtx2
stiff_mtx
end
methods
function obj = beam(stiff_mtx1, stiff_mtx2)
obj.stiff_mtx1 = stiff_mtx1;
obj.stiff_mtx2 = stiff_mtx2;
end
end
end
and
classdef parameter < handle
properties
pm1
pm2
end
methods
function obj = parameter(pm1, pm2)
obj.pm1 = pm1;
obj.pm2 = pm2;
end
end
end
and a main script to start objects:
clear; clc;
stiff_mtx1 = % a stiffness matrix.
stiff_mtx2 = % another stiffness matrix with same size.
myBeam = beam(stiff_mtx1, stiff_mtx2);
pm1 = 5;
pm2 = 10;
myPm = parameter(pm1, pm2);
So far so good, but then I want 'stiff_mtx' in beam class to be obtained like this:
myBeam.stiff_mtx = myBeam.stiff_mtx1 * myPm.pm1 + myBeam.stiff_mtx2 * myPm.pm2;
Which I tested, it works. obviously this is a communication between beam class and parameter class, and property 'stiff_mtx' is assigned after this line of command. My question is: is this the SOLID way to allow objects communicate with each other? I read in book saying in OOP, inheritance should be avoided while composition is recommended, which I agree. In the above example I could define pm1 and pm2 as properties of beam, which results in one beam class only, but I believe this is not SOLID because: 1. beam is obviously different from parameter; 2. simply adding properties in one class makes a class unnecessarily complex, which violates the SOLID principle.
I'm not sure how to allow communication among different objects, and is it SOLID to define different classes and related objects, make them communicate, or just define one big class and create one object?
Also the above line
myBeam.stiff_mtx = myBeam.stiff_mtx1 * myPm.pm1 + myBeam.stiff_mtx2 * myPm.pm2;
can it be defined as a method and put in a class? My thought is this line can be defined as a function and can be called when needed, and my program becomes a combination of OO classes and traditional functions, is this SOLID?
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Code Execution에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!