Created
August 10, 2012 07:54
-
-
Save mgenov/3312475 to your computer and use it in GitHub Desktop.
PaymentUsingFactory.java
This file contains hidden or 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
interface CreditCard { | |
void charge(Double amount); | |
} | |
interface CreditCardFactory { | |
CreditCard create(String customerId); | |
} | |
class VisaCreditCardFactory implements CreditCardFactory { | |
@Override | |
public CreditCard create(String customerId) { | |
return new CreditCard() { | |
@Override | |
public void charge(Double amount) { | |
try { | |
URLConnection urlConnection = new URL("http://mybank.com/secureurl/bank").openConnection(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
}; | |
} | |
} | |
class Payment { | |
private final CreditCardFactory factory; | |
public Payment(CreditCardFactory factory) { | |
this.factory = factory; | |
} | |
void process(String customerId, Double amount) { | |
CreditCard creditCard = factory.create(customerId); | |
creditCard.charge(amount); | |
} | |
} | |
class DummyCreditCard implements CreditCard { | |
public Double chargedAmount; | |
@Override | |
public void charge(Double amount) { | |
this.chargedAmount = amount; | |
} | |
} | |
@Test | |
public void creditCardIsChargedWhenPaymentIsProcessed() { | |
final DummyCreditCard creditCard = new DummyCreditCard(); | |
Payment payment = new Payment(new CreditCardFactory() { | |
@Override | |
public CreditCard create(String customerId) { | |
return creditCard; | |
} | |
}); | |
payment.process("george", 20d); | |
assertThat(creditCard, wasChargedWith(20d)); | |
} | |
private Matcher<DummyCreditCard> wasChargedWith(final Double expectedAmount) { | |
return new TypeSafeMatcher<DummyCreditCard>() { | |
@Override | |
protected boolean matchesSafely(DummyCreditCard dummyCreditCard) { | |
return expectedAmount.equals(dummyCreditCard.chargedAmount); | |
} | |
@Override | |
public void describeTo(Description description) { | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment