Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this use the Factory design pattern? (java)

I'm writing a small program in Java for an assignment in a OOAD class and I have a problem understanding exactly what constitutes a proper factory design pattern and how to implement it in my program.

It's a small program for payroll calculation. There is a base class called Employee and three derived (sub) classes called Hourly, Commissioned and Salaried. They each have different types of data types for payments. I'm only allowed to instantiate one object in the main class, and in the whole program. Through Polymorphism the objects should be shared between classes and I am to write a Factory method to create the objects to be assigned to THE Object.

I have the base class:

public class Employee {

protected Employee empFactory(int empType){
    if (empType == 1)
        return new Hourly();
    if (empType == 2)
        return new Commissioned();
    if (empType == 3)
        return new Salaried();
    else
        return null;
}

public static void main(String[] args) {
    // TODO code application logic here
}

And three derived classes:

public class Commissioned extends Employee
public class Hourly extends Employee
public class Salaried extends Employee

I've left out some of the datatypes and other details, I think this should be enough info. Is the factory method I have a "real" one? I've been reading about abstract and concrete factory methods and concrete products etc, but I'm still confused, don't know how to implement it. Any help or pointers would be greatly appreciated!

like image 729
Snorkelfarsan Avatar asked Jun 22 '26 17:06

Snorkelfarsan


1 Answers

You've almost got a factory method there, but not quite. The problem is that the empFactory is not static, which means that to make an Employee with it right now requires an existing Employee. Change it to static, and you've taken the first step into the Factory pattern.

The next step is to delegate the logic of the empFactory method to a separate class, a factory class. That enables a great deal more complexity (without exposing it to the caller) and is the whole core of the Factory pattern.

like image 85
Donal Fellows Avatar answered Jun 25 '26 08:06

Donal Fellows



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!