class ReportGenerator { // 하나의 클래스가 두가지 역할
void generateReport() {
// 보고서 생성 로직
}
void printReport() {
// 보고서 출력 로직
}
}
// ❌ 하나의 클래스가 두가지 역할
class ReportGenerator {
void generateReport() {
// 보고서 생성 로직
}
}
class ReportPrinter {
void printReport() {
// 보고서 출력 로직
}
}
// ⭕️ 두개의 클래스가 각각의 역할 수행
class PaymentService {
void pay(String paymentType) {
if (paymentType.equals("CreditCard")) {
// 신용카드 결제 로직
} else if (paymentType.equals("PayPal")) {
// PayPal 결제 로직
}
}
}
// ❌ 새로운 결제 수단 추가 시 기존 코드 수정 필요 → OCP 위반.
interface Payment {
void pay();
}
class CreditCardPayment implements Payment {
public void pay() {
System.out.println("Credit Card Payment");
}
}
class PayPalPayment implements Payment {
public void pay() {
System.out.println("PayPal Payment");
}
}
class PaymentService {
void processPayment(Payment payment) {
payment.pay();
}
}
// ⭕️ 새로운 결제 수단이 추가되어도 기존 PaymentService 코드를 수정할 필요 없음
class Bird {
void fly() {
System.out.println("Bird is flying");
}
}
class Penguin extends Bird {
void fly() {
throw new UnsupportedOperationException("Penguins can't fly");
}
}
// ❌ 펭귄은 날 수 없으므로, Bird 클래스를 상속받으면 문제가 발생 → LSP 위반.
interface Bird {
void move();
}
class FlyingBird implements Bird {
public void move() {
System.out.println("Bird is flying");
}
}
class Penguin implements Bird {
public void move() {
System.out.println("Penguin is swimming");
}
}
// ⭕️ Bird를 FlyingBird와 Penguin으로 분리
interface Worker {
void work();
void eat();
}
class Robot implements Worker {
public void work() {
System.out.println("Robot working");
}
public void eat() {
throw new UnsupportedOperationException("Robot can't eat");
}
}
// ❌ Robot은 eat() 메서드가 필요 없음 → ISP 위반.
interface Workable {
void work();
}
interface Eatable {
void eat();
}
class Robot implements Workable {
public void work() {
System.out.println("Robot working");
}
}
class Human implements Workable, Eatable {
public void work() {
System.out.println("Human working");
}
public void eat() {
System.out.println("Human eating");
}
}
// ⭕️ 필요한 인터페이스만 구현
interface Notification {
void send();
}
class EmailNotification implements Notification {
public void send() {
System.out.println("Email Sent");
}
}
class NotificationService {
private Notification notification;
public NotificationService(Notification notification) {
this.notification = notification;
}
void notifyUser() {
notification.send();
}
}
// ⭕️ 인터페이스를 통해 구현