What is Factory pattern?
Factory pattern is a creational pattern that defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory pattern lets a class defer instantiation to subclasses.
When to use it?
Use Factory pattern when you have "product" inheritance hierarchy and possibly add other products to that. (Product refers to an object that is returned by Factory method)
Problem
If you don't know about Simple Factory, I recommend to study it beforehand. There are plenty of resources but my blog is here.
Previously, we introduced Simple factory and we could produce variety of burgers while decoupling object creation from client code. Our burger shop has successfully earning profit and now we want to launch other burger shops in different area.
orderBurger method defines the process to sell a burger for a customer.
// This is our Client public class BurgerShop { public Burger orderBurger(BurgerType type) { // Factory is responsible for object creation Burger burger = SimpleBurgerFactory.createBurger(type); burger.prepareBun(); burger.grillPatty(); burger.addToppings(); burger.wrap(); return burger; } }
This is totally fine, but what if we launch other burger shops? Say we launch "SeaSideBurgerShop", we'll create SeaSideBurgerShop class and define its own orderBurger(). The problem is, they might forget to add toppings or do the process in the wrong order.
Problematic SeaSideBurgerShop:
public class SeaSideBurgerShop { public Burger orderBurger(BurgerType type) { Burger burger = SimpleBurgerFactory.createBurger(type); burger.prepareBun(); burger.wrap(); // Wrap a burger before grilling a patty?? burger.grillPatty(); // They forget to add toppings!! return burger; } }
To prevent this, we need a framework for our burger shops that define in which order they do the process and what to do, yet still allows things to remain flexible.
Solution
BurgerShop
This abstract class has two methods, orderBurger() and createBurger(). orderBurger() defines what to do and in which order the process should be done. This prevents burger shops to forget some process or mess up process order. creatBurger() is abstract method that lets subclasses determine which kind of burger gets made.BurgerShop subclasses
These concrete BurgerShops are responsible for creating concrete burgers. Each subclass that extends BurgerShop defines its own implementation for createBurger().Burger
This abstract class provides common interface among all the burgers and defines default behaviors.Burger subclasses
Here are our concrete products. They can implement specific behavior by overriding methods as long as they extends Burger class.
Structure
Implementation in Java
// This is our Client public class BurgerShop { public Burger orderBurger(BurgerType type) { // Factory is responsible for object creation Burger burger = SimpleBurgerFactory.createBurger(type); burger.prepareBun(); burger.grillPatty(); burger.addToppings(); burger.wrap(); return burger; } }
public class SeaSideBurgerShop { public Burger orderBurger(BurgerType type) { Burger burger = SimpleBurgerFactory.createBurger(type); burger.prepareBun(); burger.wrap(); // Wrap a burger before grilling a patty?? burger.grillPatty(); // They forget to add toppings!! return burger; } }
public enum BurgerType { BEEF, CHICKEN, FISH, VEGGIE }
public abstract class Burger { public BurgerType type; public List<string> toppings = new ArrayList(); public void prepareBun() { System.out.println("Preparing a bun"); } public void grillPatty() { if (type == null) { throw new IllegalStateException("pattyType is undefined"); } System.out.println("Grill a " + type + " patty"); } public void addToppings() { for (String item : toppings) { System.out.println("Add " + item); } } public void wrap() { System.out.println("Wrap a burger up"); } } </string>
public class CityStyleBeefBurger extends Burger { public CityStyleBeefBurger() { type = BurgerType.BEEF; List<string> items = List.of("lettuce", "pickle slices", "tomato slice", "BBQ sauce"); toppings.addAll(items); } } </string>
public class CityStyleVeggieBurger extends Burger { public CityStyleVeggieBurger() { type = BurgerType.VEGGIE; List<string> items = List.of("smoked paprika", "garlic chips", "crushed walnuts", "veggie sauce"); toppings.addAll(items); } } </string>
public class SeaSideStyleBeefBurger extends Burger { public SeaSideStyleBeefBurger() { type = BurgerType.BEEF; // Localized toppings for beef burger in seaside area List<string> items = List.of("lettuce", "pickle slices", "tomato slice", "salty sauce"); toppings.addAll(items); } // Uses localized wrapping paper @Override public void wrap() { System.out.println("Wrap with a paper with nice sea scenery"); } } </string>
public class SeaSideStyleFishBurger extends Burger { public SeaSideStyleFishBurger() { type = BurgerType.FISH; // Localized toppings for fish burger in seaside area List<string> items = List.of("red onion slices", "salty sauce", "fried shrimps"); toppings.addAll(items); } // Uses localized wrapping paper @Override public void wrap() { System.out.println("Wrap with a paper with nice sea scenery"); } } </string>
public abstract class BurgerShop { // This method provides a framework for each burger shops to order burgers public Burger orderBurger(BurgerType type) { Burger burger = createBurger(type); burger.prepareBun(); burger.grillPatty(); burger.addToppings(); burger.wrap(); return burger; } // This is our factory method. Subclasses will override this method, // provide their own implementation, determine which kind of burger gets made. public abstract Burger createBurger(BurgerType type); }
Output:
public class CityBurgerShop extends BurgerShop { @Override public Burger createBurger(BurgerType type) { return switch (type) { case BEEF -> new CityStyleBeefBurger(); case VEGGIE -> new CityStyleVeggieBurger(); default -> throw new IllegalArgumentException("unknown city burger type"); }; } }
Pitfalls
- Complex to implement because we need to create lots of classes that extends abstract creator or abstract product.
Comparison with Simple factory
- In Simple factory, there is typically one factory class to decide which type of product to create, while Factory pattern may introduce multiple factories.
- Simple factory often uses static method to create objects, which makes it easy to call but hard to extend. On the other hand, Factory method uses abstract method in super class, which acts as interface for all the factories and subclasses will provide concrete implementation for object instantiation.
You can check all the design pattern implementations here.
GitHub Repository
P.S.
I'm new to write tech blog, if you have advice to improve my writing, or have any confusing point, please leave a comment!
Thank you for reading :)
The above is the detailed content of Factory Pattern. For more information, please follow other related articles on the PHP Chinese website!

Javadevelopmentisnotentirelyplatform-independentduetoseveralfactors.1)JVMvariationsaffectperformanceandbehavioracrossdifferentOS.2)NativelibrariesviaJNIintroduceplatform-specificissues.3)Filepathsandsystempropertiesdifferbetweenplatforms.4)GUIapplica

Java code will have performance differences when running on different platforms. 1) The implementation and optimization strategies of JVM are different, such as OracleJDK and OpenJDK. 2) The characteristics of the operating system, such as memory management and thread scheduling, will also affect performance. 3) Performance can be improved by selecting the appropriate JVM, adjusting JVM parameters and code optimization.

Java'splatformindependencehaslimitationsincludingperformanceoverhead,versioncompatibilityissues,challengeswithnativelibraryintegration,platform-specificfeatures,andJVMinstallation/maintenance.Thesefactorscomplicatethe"writeonce,runanywhere"

Platformindependenceallowsprogramstorunonanyplatformwithoutmodification,whilecross-platformdevelopmentrequiressomeplatform-specificadjustments.Platformindependence,exemplifiedbyJava,enablesuniversalexecutionbutmaycompromiseperformance.Cross-platformd

JITcompilationinJavaenhancesperformancewhilemaintainingplatformindependence.1)Itdynamicallytranslatesbytecodeintonativemachinecodeatruntime,optimizingfrequentlyusedcode.2)TheJVMremainsplatform-independent,allowingthesameJavaapplicationtorunondifferen

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages such as Python and JavaScript to enhance cross-language interoperability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version
Visual web development tools
