Abstract Factory Pattern
Create an abstract class to implement Factory Pattern. Similar to Factory Pattern but we follows a Liskov Subtitution so that the subclass of Template
doesn't need to implement factory
package designpatterns.abstractfactory;
public class Template {
public final String color;
public final String templateName;
public final boolean isPublic;
public Template(String color, String templateName) {
this.color = color;
this.templateName = templateName;
isPublic = false;
}
}
package designpatterns.abstractfactory;
public abstract class TemplateFactory {
public static Template createRedTemplate(String templateName) {
return new Template("red", templateName);
}
public static Template createBlueTemplate(String templateName) {
return new Template("blue", templateName);
}
public static Template createGreenTemplate(String templateName) {
return new Template("green", templateName);
}
}
package designpatterns.abstractfactory.test;
import designpatterns.abstractfactory.Template;
import designpatterns.abstractfactory.TemplateFactory;
import org.junit.jupiter.api.Test;
class TemplateFactoryTest {
@Test
void endToEndTest_givenTemplateFactory_shouldReturnTemplate() {
Template redTemplate = TemplateFactory.createBlueTemplate("myTemplate");
Template blueTemplate = TemplateFactory.createBlueTemplate("myTemplate");
Template greenTemplate = TemplateFactory.createGreenTemplate("myTemplate");
System.out.println(redTemplate.color);
System.out.println(blueTemplate.color);
System.out.println(greenTemplate.color);
}
}