- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 347字
- 2021-06-25 20:52:33
Factory method pattern
The factory method pattern is an improvement upon the static factory. The factory class is made abstract and the code to instantiate specific products is moved to subclasses that implement an abstract method. This way, the factory class can be extended without being modified. The implementation of a factory method pattern is described in the following class diagram:

It's time for some example code. Let's assume we have a car factory. At the moment, we produce two car models: a small sports car and a large family car. In our software, the customer can decide whether they want a small car or a large car. To start with, we are creating a Vehicle class with two subclasses: SportCar and SedanCar.
Now that we have the vehicle structure, let's build the abstract factory. Please note that the factory does not have any code to create new instances:
public abstract class VehicleFactory
{
protected abstract Vehicle createVehicle(String item);
public Vehicle orderVehicle(String size, String color)
{
Vehicle vehicle = createVehicle(size);
vehicle.testVehicle();
vehicle.setColor(color);
return vehicle;
}
}
To add the code to create car instances, we subclass the VehicleFactory, creating a CarFactory. The car factory has to implement the createVehicle abstract method, which is invoked from the parent class. Practically, the VehicleFactory delegates the concrete vehicle's instantiation to the subclasses:
public class CarFactory extends VehicleFactory
{
@Override
protected Vehicle createVehicle(String size)
{
if (size.equals("small"))
return new SportCar();
else if (size.equals("large"))
return new SedanCar();
return null;
}
}
In the client, we simply create the factory and create orders:
VehicleFactory carFactory = new CarFactory();
carFactory.orderVehicle("large", "blue");
At this point, we realize how much profit a car factory can bring. It's time to extend our business, and our market research tells us that there is a high demand for trucks. So let's build a TruckFactory:
public class TruckFactory extends VehicleFactory
{
@Override
protected Vehicle createVehicle(String size)
{
if (size.equals("small"))
return new SmallTruck();
else if (size.equals("large"))
return new LargeTruck();
return null;
}
}
When an order is started, we use the following code:
VehicleFactory truckFactory = new TruckFactory();
truckFactory.orderVehicle("large", "blue");
- 演進式架構(原書第2版)
- Beginning Java Data Structures and Algorithms
- Python入門很簡單
- LabVIEW入門與實戰開發100例
- 無代碼編程:用云表搭建企業數字化管理平臺
- 樂高機器人設計技巧:EV3結構設計與編程指導
- Rust Cookbook
- C++ 從入門到項目實踐(超值版)
- Unity 5 for Android Essentials
- Node.js Design Patterns
- Learning Probabilistic Graphical Models in R
- The Professional ScrumMaster’s Handbook
- Python從入門到精通
- QGIS 2 Cookbook
- Distributed Computing in Java 9