Creational Design Pattern: Factory Pattern - BunksAllowed

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

Community

demo-image

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
1
2
3
4
5
6
7
package com.t4b.test.java.dp.cp.fp;
public interface Account {
// list of methods
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Source code of SavingsAccount.java
1
2
3
4
5
6
7
8
package com.t4b.test.java.dp.cp.fp;
public class SavingsAccount implements Account {
// define the methods declared in Account Interface
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Source code of TermDepositAccount.java
1
2
3
4
5
6
7
8
package com.t4b.test.java.dp.cp.fp;
public class TermDepositAccount implements Account {
// define the methods declared in Account Interface
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Source code of AccountFactory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Source code of TestMain.java
1
2
3
4
5
6
7
8
9
10
11
12
13
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");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.