Abstract Factory Pattern: provides an interface for creating families of
related or dependent objects without specifying concrete classes.
Example
Account.java
package com.abstractfactorypattern.example; public interface Account { //define generic methods required }
SavingsAccount.java
package com.abstractfactorypattern.example; public class SavingsAccount implements Account { public String toString() { return "Savings Account created Succesfully"; } }
CheckingAccount.java
package com.abstractfactorypattern.example; public class CheckingAccount implements Account { public String toString() { return "Checking Account created Succesfully"; } }
LoanAccount.java
package com.abstractfactorypattern.example; public class LoanAccount implements Account { public String toString() { return "Loan Account created Succesfully"; } }
AbstractAccountFactory.java
package com.abstractfactorypattern.example; public abstract class AbstractAccountFactory { public abstract Account createSavingsAccount(); public abstract Account createCheckingAccount(); public abstract Account createLoanAccount(); }
AccountFactory.java
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
package com.abstractfactorypattern.example; import java.util.ArrayList; import java.util.List; public class AccountTestDrive { public static void main(String[] args) { ListHomeaccountList= 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); } } }
well done
ReplyDelete