Abstract Factory Pattern

Abstract Factory Pattern Java Design Pattern Tutorial
Abstract Factory Pattern: provides an interface for creating families of related or dependent objects without specifying concrete classes.

Example

Account.java
1
2
3
4
5
package com.abstractfactorypattern.example;
 
public interface Account {
 //define generic methods required
}
SavingsAccount.java
1
2
3
4
5
6
7
8
9
package com.abstractfactorypattern.example;
 
public class SavingsAccount implements Account {
  
 public String toString() {
  return "Savings Account created Succesfully";
 }
  
}
CheckingAccount.java
1
2
3
4
5
6
7
8
9
package com.abstractfactorypattern.example;
 
public class CheckingAccount implements Account {
 
 public String toString() {
  return "Checking Account created Succesfully";
 }
 
}
LoanAccount.java
1
2
3
4
5
6
7
8
9
package com.abstractfactorypattern.example;
 
public class LoanAccount implements Account {
 
 public String toString() {
  return "Loan Account created Succesfully";
 }
 
}
AbstractAccountFactory.java
1
2
3
4
5
6
7
8
package com.abstractfactorypattern.example;
 
public abstract class AbstractAccountFactory {
 public abstract Account createSavingsAccount();
 public abstract Account createCheckingAccount();
 public abstract Account createLoanAccount();
  
}
AccountFactory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.abstractfactorypattern.example;
 
public class AccountFactory extends AbstractAccountFactory {
  
 public Account createSavingsAccount(){
  return new SavingsAccount();
 }
 public Account createCheckingAccount(){
  return new CheckingAccount();
 }
 public Account createLoanAccount(){
  return new LoanAccount();
 }
  
}
AccountTestDrive.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.abstractfactorypattern.example;
 
import java.util.ArrayList;
import java.util.List;
 
public class AccountTestDrive {
  
 public static void main(String[] args) {
  List<account> accountList= new ArrayList<>();
  //AbstractAccount defines Account Factories
  AbstractAccountFactory accountFactory = new AccountFactory();
  //Using Factory to get Account instance
  Account savingsAccount = accountFactory.createSavingsAccount();
  Account checkingAccount = accountFactory.createCheckingAccount();
  Account loanAccount = accountFactory.createLoanAccount();
  accountList.add(savingsAccount);
  accountList.add(checkingAccount);
  accountList.add(loanAccount);
   
  for (Account account : accountList) {
   System.out.println(account);
  }
   
 }
}
</account>



Home

1 comment: