What is the difference between loose coupling and tight coupling in the object oriented paradigm?

前端 未结 16 1965
粉色の甜心
粉色の甜心 2020-11-22 08:03

Can any one describe the exact difference between loose coupling and tight coupling in Object oriented paradigm?

16条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 08:55

    If an object's creation/existence dependents on another object which can't be tailored, its tight coupling. And, if the dependency can be tailored, its loose coupling. Consider an example in Java:

    class Car {
    
        private Engine engine = new Engine( "X_COMPANY" ); // this car is being created with "X_COMPANY" engine
        // Other parts
    
        public Car() { 
            // implemenation 
        }
    
    }
    

    The client of Car class can create one with ONLY "X_COMPANY" engine.

    Consider breaking this coupling with ability to change that:

    class Car {
    
        private Engine engine;
        // Other members
    
        public Car( Engine engine ) { // this car can be created with any Engine type
            this.engine = engine;
        }
    
    }
    

    Now, a Car is not dependent on an engine of "X_COMPANY" as it can be created with types.

    A Java specific note: using Java interfaces just for de-coupling sake is not a proper desing approach. In Java, an interface has a purpose - to act as a contract which intrisically provides de-coupling behavior/advantage.

    Bill Rosmus's comment in accepted answer has a good explanation.

提交回复
热议问题