1.7 KiB
Simple Factory Pattern in Java
This project demonstrates the Simple Factory design pattern in Java. It includes an abstract product interface, concrete product implementations, and a factory class to create product instances based on specified types.
Project Structure
simple-factory-java
├── src
│ └── main
│ └── java
│ ├── Product.java
│ ├── ConcreteProductA.java
│ ├── ConcreteProductB.java
│ └── Factory.java
├── pom.xml
└── README.md
Files Description
-
Product.java: Defines the
Productinterface with basic methods that all products must implement, such asuse(). -
ConcreteProductA.java: Implements the
Productinterface, defining the behavior of Concrete Product A and overriding theuse()method. -
ConcreteProductB.java: Implements the
Productinterface, defining the behavior of Concrete Product B and overriding theuse()method. -
Factory.java: Defines the
Factoryclass, which contains a static methodcreateProduct(String type)that returns the appropriate product instance based on the provided type. -
pom.xml: Maven configuration file that defines the project's dependencies and build settings.
Usage
To use this project, you can call the Factory.createProduct(String type) method with either "A" or "B" to get an instance of ConcreteProductA or ConcreteProductB, respectively. Then, you can invoke the use() method on the product instance to see its behavior.
Build and Run
- Ensure you have Maven installed on your machine.
- Navigate to the project directory.
- Run
mvn clean installto build the project. - Use the generated classes in your Java application as needed.