factory pattern in matlab

Here is an example implementation of the Factory Pattern in MATLAB:

main.m
classdef ShapeFactory
    methods (Static)
        function shape = createShape(type, varargin)
            switch type
                case 'circle'
                    shape = Circle(varargin{:});
                case 'square'
                    shape = Square(varargin{:});
                otherwise
                    error('Unsupported shape type');
            end
        end
    end
end

classdef Circle
    properties
        radius
    end
    
    methods
        function obj = Circle(r)
            obj.radius = r;
        end
        
        function area = getArea(obj)
            area = pi * obj.radius^2;
        end
    end
end

classdef Square
    properties
        side
    end
    
    methods
        function obj = Square(s)
            obj.side = s;
        end
        
        function area = getArea(obj)
            area = obj.side^2;
        end
    end
end
892 chars
47 lines

In this implementation, we define a ShapeFactory class that has a static createShape method. This method takes a shape type and any additional arguments needed to create the shape, and returns a new instance of the specified shape type. The switch statement inside the createShape method is responsible for determining which type of shape to create based on the input type string.

We then define two classes that represent different types of shapes: Circle and Square. These classes both have a single property (radius for Circle, side for Square) and a getArea method that calculates the area of the shape.

With this implementation, we can create new instances of different types of shapes by calling ShapeFactory.createShape with the appropriate type string and any necessary arguments:

main.m
circle = ShapeFactory.createShape('circle', 4);
square = ShapeFactory.createShape('square', 5);

circle.getArea() % returns approximately 50.27
square.getArea() % returns 25
174 chars
6 lines

This implementation of the Factory Pattern allows us to abstract away the details of shape creation and focus on using the created shapes. It also makes it easy to add new shapes to our system in the future by simply creating a new class and adding a case to the switch statement in the ShapeFactory class.

gistlibby LogSnag