用Java代碼實(shí)現(xiàn)單一職責(zé)原則課堂Book案例
設(shè)我們有一個(gè)Book類,表示一本書,其中包含書的名稱、作者和價(jià)格。我們可以按照單一職責(zé)原則將其分解為三個(gè)類:Book、Author和Price。
Book類負(fù)責(zé)維護(hù)書的名稱、作者和價(jià)格,同時(shí)提供一些查詢和修改方法。
```java
public class Book {
private String name;
private Author author;
private Price price;
public Book(String name, Author author, Price price) {
this.name = name;
this.author = author;
this.price = price;
}
public String getName() {
return name;
}
public Author getAuthor() {
return author;
}
public Price getPrice() {
return price;
}
public void setName(String name) {
this.name = name;
}
public void setAuthor(Author author) {
this.author = author;
}
public void setPrice(Price price) {
this.price = price;
}
}
```
Author類負(fù)責(zé)維護(hù)書的作者信息。
```java
public class Author {
private String name;
public Author(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
```
Price類負(fù)責(zé)維護(hù)書的價(jià)格信息。
```java
public class Price {
private double value;
public Price(double value) {
this.value = value;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}
```
通過(guò)這種方式,我們將Book類的職責(zé)分解為三個(gè)類,每個(gè)類都只負(fù)責(zé)自己的職責(zé)。這樣可以使代碼更加清晰、易于維護(hù)和擴(kuò)展。