欢迎光临散文网 会员登陆 & 注册

用Java代码实现单一职责原则课堂Book案例

2023-03-14 14:34 作者:酸奶公园  | 我要投稿

设我们有一个Book类,表示一本书,其中包含书的名称、作者和价格。我们可以按照单一职责原则将其分解为三个类:Book、Author和Price。


Book类负责维护书的名称、作者和价格,同时提供一些查询和修改方法。


```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类负责维护书的作者信息。


```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类负责维护书的价格信息。


```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;

}

}

```


通过这种方式,我们将Book类的职责分解为三个类,每个类都只负责自己的职责。这样可以使代码更加清晰、易于维护和扩展。


用Java代码实现单一职责原则课堂Book案例的评论 (共 条)

分享到微博请遵守国家法律