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
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
package com.factorypattern.example; public class SavingsAccount extends Account { @Override public String getAccountType() { return "Saving Account"; } }
CheckingAccount.java
package com.factorypattern.example; public class CheckingAccount extends Account { @Override public String getAccountType() { return "Checking Account"; } }
LoanAccount.java
package com.factorypattern.example; public class LoanAccount extends Account{ @Override public String getAccountType() { return "Loan Account"; } }
SimpleAccountFactory.java
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
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
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