Creational Design Pattern: Factory Pattern - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Creational Design Pattern: Factory Pattern

Share This



The Factory Pattern, or the Factory Method Pattern, involves defining an interface or abstract class for producing objects while allowing subclasses to determine which class to instantiate. Subclasses have the responsibility of instantiating the class.

The Factory Method Pattern is alternatively referred to as the Virtual Constructor. The primary benefit of implementing the Factory Design Pattern is its ability to create objects without specifying the exact class of the object that will be created. This allows for greater flexibility and modularity in the code, as it separates the object creation logic from the rest of the codebase.

The Factory Method Pattern enables sub-classes to determine the specific type of objects to be created.

It facilitates loose coupling by reducing the code's requirement to bind application-specific classes. This implies that the code only interacts with the resulting interface or abstract class, allowing it to function with any classes that implement that interface or extend that abstract class.

Source code of Account.java
package com.t4b.test.java.dp.cp.fp; public interface Account { // list of methods }
Source code of SavingsAccount.java
package com.t4b.test.java.dp.cp.fp; public class SavingsAccount implements Account { // define the methods declared in Account Interface }
Source code of TermDepositAccount.java
package com.t4b.test.java.dp.cp.fp; public class TermDepositAccount implements Account { // define the methods declared in Account Interface }
Source code of AccountFactory.java
package com.t4b.test.java.dp.cp.fp; public class AccountFactory { Account createAccount(String accType) { if (accType.equals("Savings")) { return new SavingsAccount(); } else if (accType.equals("TermDeposit")) { return new TermDepositAccount(); } return null; } }
Source code of TestMain.java
package com.t4b.test.java.dp.cp.fp; public class TestMain { public static void main(String[] args) { AccountFactory accountFactory = new AccountFactory(); Account savAccount = accountFactory.createAccount("Savings"); Account tdAccount = accountFactory.createAccount("TermDeposit"); } }

Happy Exploring!

No comments:

Post a Comment