강한 결합

코드를 직접적으로 사용하고 있다.

public class Coupling {
	public static void main(String[] args) {
		Person person = new Person(new IPhone());
		person.call();
		person.camera();
	}
	static class Person{
		IPhone iPhone;
		
		public Person(IPhone iPhone) {
			this.iPhone = iPhone;
		}
		public void call() {
			iPhone.call();
		}
		public void camera() {
			iPhone.camera();
		}
	}
	
	static class IPhone{
		public void call() {
			System.out.println("전화걸기");
		}
		public void camera() {
			System.out.println("사진찍기");
		}
	}
}

변경

사용자가 아이폰 대신 갤럭시를 쓰려고 한다.

단순히 갤럭시 클래스를 새로 만들고 사용하려고 했지만, 기존 아이폰과 강하게 결합되어 변경을 할 수가 없다.

public class Coupling2 {
	public static void main(String[] args) {
		Person person = new Person(new IPhone());
		//강한 결합으로 갤럭시를 쓰고 싶다면
		//기존 Person 코드의 수정이 필요하다.
//		Person person2 = new Person(new Galaxy());
		person.call();
		person.camera();
	}
	
	static class Person{
		IPhone iPhone;
		
		public Person(IPhone iPhone) {
			this.iPhone = iPhone;
		}
		public void call() {
			iPhone.call();
		}
		public void camera() {
			iPhone.camera();
		}
	}
	static class Galaxy{
		public void call() {
			System.out.println("전화걸기");
		}
		public void camera() {
			System.out.println("사진찍기");
		}
	}
	
	static class IPhone{
		public void call() {
			System.out.println("전화걸기");
		}
		public void camera() {
			System.out.println("사진찍기");
		}
	}
}

인터페이스를 이용한 느슨한 결합

중간에 추상화된 것에 의존하게 됐다. 따라서 앞으로 새로운 스마트폰이 생겨도 Person 클래스는 변경이 일어나지 않는다.

public class Coupling3 {
	public static void main(String[] args) {
		Person person = new Person(new IPhone());
		//강한 결합으로 갤럭시를 쓰고 싶다면
		//기존 Person 코드의 수정이 필요하다.
		Person person2 = new Person(new Galaxy());
		person.call();
		person.camera();
		person2.call();
		person2.camera();
	}
	
	static class Person{
		SmartPhone phone;
		
		public Person(SmartPhone phone) {
			this.phone = phone;
		}
		void call() {
			phone.call();
		}
		void camera() {
			phone.camera();
		}
	}
	interface SmartPhone {
		void call();
		void camera();
	}
	
	static class Galaxy implements SmartPhone{
		public void call() {
			System.out.println("전화걸기");
		}
		public void camera() {
			System.out.println("사진찍기");
		}
	}
	
	static class IPhone implements SmartPhone{
		public void call() {
			System.out.println("전화걸기");
		}
		public void camera() {
			System.out.println("사진찍기");
		}
	}
}

 

+ Recent posts