design pattern in java code example
Example 1: java builder pattern example
public class BankAccount {
public static class Builder {
private long accountNumber;
private String owner;
private String branch;
private double balance;
private double interestRate;
public Builder(long accountNumber) {
this.accountNumber = accountNumber;
}
public Builder withOwner(String owner){
this.owner = owner;
return this;
}
public Builder atBranch(String branch){
this.branch = branch;
return this;
}
public Builder openingBalance(double balance){
this.balance = balance;
return this;
}
public Builder atRate(double interestRate){
this.interestRate = interestRate;
return this;
}
public BankAccount build(){
BankAccount account = new BankAccount();
account.accountNumber = this.accountNumber;
account.owner = this.owner;
account.branch = this.branch;
account.balance = this.balance;
account.interestRate = this.interestRate;
return account;
}
}
private BankAccount() {
}
}
BankAccount account = new BankAccount.Builder(1234L)
.withOwner("Marge")
.atBranch("Springfield")
.openingBalance(100)
.atRate(2.5)
.build();
BankAccount anotherAccount = new BankAccount.Builder(4567L)
.withOwner("Homer")
.atBranch("Springfield")
.openingBalance(100)
.atRate(2.5)
.build();
Example 2: java design patterns
public static ThreadSafeSingleton getInstanceDoubleLocking() {
if (instance == null) {
synchronized (ThreadSafeSingleton.class) {
if (instance == null) {
instance = new ThreadSafeSingleton();
}
}
}
return instance;
}
Example 3: pyramid pattern in java
public class Pyramid_Pattern {
static void printPattern(int n)
{
int j, k = 0;
for (int i = 1; i <= n; i++) {
if (i % 2 != 0) {
for (j = k + 1; j < k + i; j++)
System.out.print(j + "*");
System.out.println(j++);
k = j;
}
else {
k = k + i - 1;
for (j = k; j > k - i + 1; j--)
System.out.print(j + "*");
System.out.println(j);
}
}
}
public static void main(String args[])
{
int n = 5;
printPattern(n);
}
}