<<< Structured programming     Index     Inheritance >>>

4. Encapsulation

  • Create classes for each printer type:

    
    class LazerPrinter { /*etc.*/ };
    
    class InkjetPrinter { /*etc.*/ };
    
    class FaxMachine { /*etc.*/ };
    
    void print( Printer* pr )
    {
        if ( pr->type == 'L' ) {
            LazerPrinter.print( /*params*/ );
    
        } else if ( pr->type == 'I' ) {
            InkjetPrinter.print( /*params*/ );
    
        } else if ( pr->type == 'F' ) {
            FaxMachine.print( /*params*/ );
        }
    }
    
    
  • Better!

    However...

    • if-else continues to control the logic in the original print( ) function and that adds to the complexity of the implementation.

<<< Structured programming     Index     Inheritance >>>