Skip to content

Instantly share code, notes, and snippets.

@onozaty
Last active July 17, 2018 03:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onozaty/c96cf7a630c2cfa85c6342930e0c7899 to your computer and use it in GitHub Desktop.
Save onozaty/c96cf7a630c2cfa85c6342930e0c7899 to your computer and use it in GitHub Desktop.
2018-07-11 リファクタリング
package com.example;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class MeatMenu {
private final List<Menu> allMenus;
public MeatMenu(List<Menu> allMenus) {
this.allMenus = allMenus;
}
private List<Menu> getAllMenus() {
return allMenus;
}
public String createRequestWithAllMeatMenu() {
return getAllMenus().stream()
.filter(Menu::hasMeat)
.map(Menu::getName)
.collect(Collectors.joining(", "));
}
public String createRequestWithMeatMenuFor5000yen() {
Wallet wallet = new Wallet(5000);
return getAllMenus().stream()
// 金額が低いもの順で
.sorted(Comparator.comparing(Menu::getPriceYen))
// 肉料理を順番に注文していって、支払い不可能な金額のものは除外
.filter(Menu::hasMeat)
.filter(menu -> wallet.pay(menu.getPriceYen())) // Java9以降ならばtakeWhileを使うべき
.map(Menu::getName)
.collect(Collectors.joining(", "));
}
public static class Wallet {
private int money;
public Wallet(int money) {
this.money = money;
}
public boolean pay(int price) {
if (money < price) {
// 残高不足
return false;
}
money -= price;
return true;
}
}
public static class Menu {
private final String name;
private final boolean hasMeat;
private final int priveYen;
public Menu(String name, boolean hasMeat, int priveYen) {
super();
this.name = name;
this.hasMeat = hasMeat;
this.priveYen = priveYen;
}
public String getName() {
return name;
}
public boolean hasMeat() {
return hasMeat;
};
public int getPriceYen() {
return priveYen;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment