面向對象基本原則 - SOLID原則
SOLID原則
SOLID原則包含五條原則,每條原則取首字母即SOLID。
Single Responsibility Principle 單一責任原則
定義:一個類只應該做一件事情
一個類如果需要做多個事情,那么就要拆分這個類。
public class User {
private String username;
private String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
}
Open Closed Principle 開放封閉原則
定義:實體對擴展應該是開放的,對修改應該是封閉的
通過繼承和接口實現多態,而不是直接修改現有類的代碼。
interface Animal {
void makeSound();
}
class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
Liskov Substitution Principle 里氏替換原則
定義:子類必須能夠替換其父類而不會引發錯誤。
描述:子類必須能夠替換其父類,且程序的當功能前不會改變。
例子:如果有一個父類的方法返回一個對象的類型,那么任何使用這個返回值的代碼在子類替換后也應該正常工作。
class Sms {
public void sendSms(double phoneNo) {
// ...
}
}
class TencentSms extends Sms {
public void sendSms(double phoneNo) {
// ...
}
}
class AliSms extends Sms {
public void sendSms(double phoneNo) {
// ...
}
}
class Run {
private Sms sms = new Sms();
public void run(double phoneNo) {
sms.sendSms(phoneNo);
}
}
The Interface Segregation Principle 接口分離原則
定義:客戶端不應該被強制依賴于它們不使用的接口。多個專門的接口比復合的單一接口好。
// 大的接口,包含了很多方法
public interface LargeInterface {
void method1();
void method2();
void method3();
// ...更多方法...
}
// 拆分后的接口1,只包含客戶端需要的方法1
public interface SmallInterface1 {
void method1();
}
// 拆分后的接口2,只包含客戶端需要的方法2和3
public interface SmallInterface2 {
void method2();
void method3();
}
// 具體實現類,實現了拆分后的接口
public class ConcreteClass implements SmallInterface1, SmallInterface2 {
@Override
public void method1() { // 實現方法1 }
@Override
public void method2() { // 實現方法2 }
@Override
public void method3() { // 實現方法3 }
}
The Dependency Inversion Principle 依賴倒置原則
定義:高層模塊不應該依賴于低層模塊,它們都應該依賴于抽象;抽象不應該依賴于細節,具體實現應該依賴于抽象。
// 定義一個抽象接口
public interface MessageService {
void sendMessage(String message);
}
// 實現抽象接口的具體類
public class EmailMessageService implements MessageService {
@Override
public void sendMessage(String message) {
// 實現發送電子郵件的邏輯
}
}
// 實現抽象接口的具體類
public class SmsMessageService implements MessageService {
@Override
public void sendMessage(String message) {
// 實現發送短信的邏輯
}
}
// 高層模塊,依賴于抽象接口MessageService,而不是具體類
public class NotificationSystem {
private MessageService messageService;
public NotificationSystem(MessageService messageService) {
this.messageService = messageService;
}
public void notifyUser(String message, String recipient) {
messageService.sendMessage(message);
}
}
浙公網安備 33010602011771號