Last active
July 15, 2018 11:34
-
-
Save onozaty/5dfdf0f9538abe839befdfe2a7f5d7ab to your computer and use it in GitHub Desktop.
2018-05-16 リファクタリング
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 maney) { | |
this.money = maney; | |
} | |
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