- loose coupling
인터페이스 - 특정 기능만 필수로 존재하면 되. 특정 기능이 '어떻게' 존재해야 하는지, 그 종류는
그때그때마다 정하면 되. (interface)의 역할
- tight coupling
특정 기능이 특정 방식으로 구현된 클래스를 attribute로 가짐
특정 기능이 무조건 attribute 클래스의 방식이어야 해.
class Engine {
void run() {
// 엔진 실행 코드
}
}
class Robot {
Engine eng = new Engine();
eng.run();
}
이 robot class를 tight coupling이 아닌, loose coupling을 통해선 어떻게 구현해?
ChatGPT
Loose coupling을 실현하려면 클래스 간의 의존성을 최소화하고, 의존성 주입 또는 인터페이스 구현을 통해 유연성을 확보해야 합니다. 아래는 Robot 클래스를 loose coupling으로 변경하는 방법 중 하나입니다.
interface Engine {
void run();
}
class StandardEngine implements Engine {
void run() {
// 표준 엔진 실행 코드
}
}
class TurboEngine implements Engine {
void run() {
// 터보 엔진 실행 코드
}
class Robot {
Engine eng;
Robot(Engine engine) {
this.eng = engine;
}
void start() {
eng.run();
}
}
위 코드에서는 Engine 인터페이스를 도입하여 StandardEngine 및 TurboEngine과 같은 구체적인 엔진 구현을 만들었습니다. 그런 다음 Robot 클래스는 Engine 인터페이스에 대한 참조를 가지며, 생성자를 통해 원하는 종류의 엔진을 주입받습니다.
이렇게 하면 Robot 클래스는 특정 엔진 구현에 대한 직접적인 의존성을 갖지 않으며, 필요에 따라 다른 종류의 엔진을 사용할 수 있습니다. 이것이 의존성 주입을 통한 loose coupling의 예입니다.
You should try to achieve loose coupling. Loose coupling makes parts of your code less interdependent on each other. The easiest way you can achieve it is with interfaces and dependency injection.
Parts of your code should have high cohesion, so that they can be more focused. This will make them more reusable and easier to test.
Example 1:
class MakeCar is
method makeWheels() is
return wheels
method makeEngine() is
return engine
method installEngine()
...
method installWheels()
...
Example 2:
class Wheels is
constructor of Wheels is ...
method installWheels() is ...
class Engine is
constructor of Engine is ...
method installEngine() is ...
class makeCar is
Engine eng = new Engine()
Wheels wh = new Wheels()
eng.installEngine()
wh.installWheels()