Factory Design Pattern

Factory Design Pattern also known as Factory Method Design Pattern, is one of the cretional desing pattern. In some scenarios where a super class has multiple sub classes and based on the input provided it returns one of the sub-class objects.

The facotory takes the responsibility of creating the object.
it uses Interface for object creation rather than an individual-implemented class hence providing a layer of abstraction.

package org.wesome.design.patterns;

public enum AppleEnum {
    MACINTOSH, FUJI
}
package org.wesome.design.patterns;

public abstract class Apple {
    public abstract AppleEnum getName();

    public abstract String getTaste();
}
package org.wesome.design.patterns;

public class AppleFactory {
    public static Apple getApple(AppleEnum name, String taste) {
        switch (name) {
            case MACINTOSH:
                return new Macintosh(name, taste);
            case FUJI:
                return new Fuji(name, taste);
            default:
                throw new IllegalArgumentException("invalid Apple Type");
        }
    }
}
package org.wesome.design.patterns;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;

@Getter
@ToString
@AllArgsConstructor
public class Fuji extends Apple {
    private AppleEnum name;
    private String taste;
}
package org.wesome.design.patterns;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;

@Getter
@ToString
@AllArgsConstructor
public class Macintosh extends Apple {
    private AppleEnum name;
    private String taste;
}
package org.wesome.design.patterns;

public class Factory {
    public static void main(String[] args) {
        Apple macintosh = AppleFactory.getApple(AppleEnum.MACINTOSH, "sweet");
        Apple fuji = AppleFactory.getApple(AppleEnum.FUJI, "sour");
        System.out.println("Macintosh " + macintosh);
        System.out.println("Fuji " + fuji);
    }
}
package org.wesome.design.patterns;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class AbstractTest {
    @Test
    void testMacintosh() {
        Apple macintosh = AppleFactory.getApple(AppleEnum.MACINTOSH, "sweet");
        Assertions.assertTrue(macintosh instanceof Apple);
        Assertions.assertTrue(macintosh instanceof Macintosh);
    }

    @Test
    void testFuji() {
        Apple fuji = AppleFactory.getApple(AppleEnum.FUJI, "sour");
        Assertions.assertTrue(fuji instanceof Apple);
        Assertions.assertTrue(fuji instanceof Fuji);
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

follow us on