Factory Pattern

Factory Pattern Java Design Pattern Tutorial
Factory Pattern: Defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to the subclasses.

Example

Account.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.factorypattern.example;
 
public abstract class Account {
 
 public void deposit() {
  System.out.println("Now you can deposit  Amount into your Account");
 }
 
 public void withdraw() {
  System.out.println("Now you can Withdraw Amount into your Account");
 }
 
 public abstract String getAccountType();
}
SavingsAccount.java
1
2
3
4
5
6
7
8
9
10
package com.factorypattern.example;
 
public class SavingsAccount extends Account {
 
 @Override
 public String getAccountType() {
  return "Saving Account";
 }
  
}
CheckingAccount.java
1
2
3
4
5
6
7
8
9
10
package com.factorypattern.example;
 
public class CheckingAccount extends Account {
 
 @Override
 public String getAccountType() {
  return "Checking Account";
 }
  
}
LoanAccount.java
1
2
3
4
5
6
7
8
9
10
package com.factorypattern.example;
 
public class LoanAccount extends Account{
 
 @Override
 public String getAccountType() {
  return "Loan Account";
 }
 
}
SimpleAccountFactory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.factorypattern.example;
 
public class SimpleAccountFactory {
 
 public Account openAccount(String type) {
  Account account = null;
  if (type.equals("saving")) {
   account = new SavingsAccount();
  } else if (type.equals("checking")) {
   account = new CheckingAccount();
  } else if (type.equals("loan")) {
   account = new LoanAccount();
  }
  return account;
 }
}
Bank.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.factorypattern.example;
 
public class Bank {
 
 SimpleAccountFactory accountFactory;
 
 public Bank(SimpleAccountFactory accountFactory) {
  super();
  this.accountFactory = accountFactory;
 }
 
 public void openAccount(String type) {
  Account account = accountFactory.openAccount(type);
  System.out.format("Account Type: %s Opened successfully \n",account.getAccountType());
  account.deposit();
 }
 
}
AccountTestDrive.java
1
2
3
4
5
6
7
8
9
package com.factorypattern.example;
 
public class AccountTestDrive {
 public static void main(String[] args) {
  SimpleAccountFactory accountFactory = new SimpleAccountFactory();
  Bank bank = new Bank(accountFactory);
  bank.openAccount("saving");
 }
}


Home

No comments:

Post a Comment