Java

Families of cross-platform GUI components and their production

In this example, buttons and checkboxes will act as products. They have two variants: macOS and Windows.

The abstract factory defines an interface for creating buttons and checkboxes. There are two concrete factories, which return both products in a single variant.

Client code works with factories and products using abstract interfaces. It makes the same client code working with many product variants, depending on the type of factory object.

buttons: First product hierarchy

buttons/Button.java

package refactoring_guru.abstract_factory.example.buttons;

/**
 * Abstract Factory assumes that you have several families of products,
 * structured into separate class hierarchies (Button/Checkbox). All products of
 * the same family have the common interface.
 *
 * This is the common interface for buttons family.
 */
public interface Button {
    void paint();
}

buttons/MacOSButton.java

buttons/WindowsButton.java

checkboxes: Second product hierarchy

checkboxes/Checkbox.java

checkboxes/MacOSCheckbox.java

checkboxes/WindowsCheckbox.java

factories

factories/GUIFactory.java: Abstract factory

factories/MacOSFactory.java: Concrete factory (macOS)

factories/WindowsFactory.java: Concrete factory (Windows)

app

app/Application.java: Client code

Demo.java: App configuration

OutputDemo.txt: Execution result

Last updated