bridge pattern in matlab

The Bridge pattern is used when we need to decouple an abstraction from its implementation so that the two can vary independently. In Matlab, this can be implemented as follows:

  1. Create an abstraction class with some methods:
main.m
classdef Abstraction < handle
    properties(Access = protected)
        implementor BridgeInterface
    end
    
    methods
        function obj = Abstraction(implementor)
            obj.implementor = implementor;
        end
        
        function operation(obj)
            obj.implementor.operationImp();
        end
    end
    
end
343 chars
17 lines
  1. Create an implementor interface with some methods:
main.m
classdef BridgeInterface < handle
    methods(Abstract)
        operationImp(obj)
    end
end
94 chars
6 lines
  1. Create some concrete implementor classes that implement the BridgeInterface:
main.m
classdef ConcreteImplementorA < BridgeInterface
    methods
        function operationImp(obj)
            % implementation for ConcreteImplementorA
        end
    end
end

classdef ConcreteImplementorB < BridgeInterface
    methods
        function operationImp(obj)
            % implementation for ConcreteImplementorB
        end
    end
end
347 chars
16 lines
  1. Use the abstraction to call the operation defined in the implementors:
main.m
implementorA = ConcreteImplementorA();
abstractionA = Abstraction(implementorA);
abstractionA.operation(); % calls ConcreteImplementorA's implementation

implementorB = ConcreteImplementorB();
abstractionB = Abstraction(implementorB);
abstractionB.operation(); % calls ConcreteImplementorB's implementation
307 chars
8 lines

This way, if we need to change an implementation, we can do it without affecting the abstraction code.

related categories

gistlibby LogSnag