Skip to content

Instantly share code, notes, and snippets.

@abruzzi
Forked from kt3k/BankAccount.java
Created January 3, 2017 06:39
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 abruzzi/b17d6a021b3347365f88a22de31dd149 to your computer and use it in GitHub Desktop.
Save abruzzi/b17d6a021b3347365f88a22de31dd149 to your computer and use it in GitHub Desktop.
BankAccount DCI example in Java
package org.kt3k.bankaccount;
public class BankAccount {
private String id;
private Integer balance;
public BankAccount(String id, Integer balance) {
this.id = id;
this.balance = balance;
}
public void increase(Integer money) {
this.balance += money;
}
public void decrease(Integer money) {
this.balance -= money;
}
public Integer getBalance() {
return this.balance;
}
public String getId() {
return this.id;
}
}
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
testCompile 'junit:junit:4.11'
}
package org.kt3k.bankaccount;
public class TransferContext {
private BankAccountSender sender;
private BankAccountReceiver receiver;
public TransferContext(BankAccount sender, BankAccount receiver) {
this.sender = new BankAccountSender(sender);
this.receiver = new BankAccountReceiver(receiver);
}
static private class BankAccountSender {
private BankAccount actor;
public BankAccountSender(BankAccount actor) {
this.actor = actor;
}
public void send(Integer money, BankAccountReceiver receiver) {
this.actor.decrease(money);
receiver.onReceive(money);
}
}
static private class BankAccountReceiver {
private BankAccount actor;
public BankAccountReceiver(BankAccount actor) {
this.actor = actor;
}
public void onReceive(Integer money) {
this.actor.increase(money);
}
}
public void transfer(Integer money) {
this.sender.send(money, this.receiver);
}
}
package org.kt3k.bankaccount;
import org.junit.Test;
import static org.junit.Assert.*;
public class TransferContextTest {
@Test
public void testTransfer() {
BankAccount a = new BankAccount("abc123", 15000);
BankAccount b = new BankAccount("def456", 25000);
new TransferContext(a, b).transfer(5000);
assertEquals((Integer)10000, a.getBalance());
assertEquals((Integer)30000, b.getBalance());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment