Created
June 1, 2018 07:52
-
-
Save isatimur/be96127cebd2aee0ccb367d35660b278 to your computer and use it in GitHub Desktop.
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
class Cash { | |
private final Exchange exchange; | |
private final int cents; | |
public Cash(Exchange exch, int cents) { | |
this.exchange = exch; | |
this.cents = cents; | |
} | |
public Cash in(String currency) { | |
return new Cash( | |
this.exchange, | |
this.cents * this.exchange.rate( | |
"USD",currency | |
) | |
); | |
} | |
} | |
//Mockito example | |
//Exchange exchange = Mockito.mock(Exchange.class); | |
//Mockito.doReturn(1.15) | |
// .when(exchange) | |
// .rate("USD","EUR") | |
//Cash dollar = new Cash(exchange, 500) | |
//cash euro = dollar.in("EUR") | |
//assert "5.75".equals(euro.toString()) | |
//первый пример fake объекта | |
interface Exchange { | |
float rate(String origin, String target); | |
final class Fake implements Exchange { | |
@Override | |
float rate(String origin, String target) { | |
return 1.2345; | |
} | |
} | |
} | |
// затем добавляем новый метод | |
interface Exchange { | |
//например здесь может быть логика что по умолчанию кеш будет конвертироваться из долларов USD | |
float rate(String target); | |
float rate(String origin, String target); | |
} | |
//На наш код с моками это никак не повлияет а вот если делать fake то придётся написать ноаую имплементацию как здесь | |
interface Exchange { | |
float rate(String target); | |
float rate(String origin, String target); | |
final class Fake implements Exchange { | |
@Override | |
float rate(String target) { | |
return this.rate("USD", target); | |
} | |
@Override | |
float rate(String origin, String target) { | |
return 1.2345; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment