- 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");
- Implementing VMware Horizon 7(Second Edition)
- Python概率統(tǒng)計
- 造個小程序:與微信一起干件正經事兒
- R語言編程指南
- 用戶體驗增長:數字化·智能化·綠色化
- 微信小程序入門指南
- SQL 經典實例
- Linux Shell核心編程指南
- Access 2010數據庫應用技術實驗指導與習題選解(第2版)
- 軟件工程與UML案例解析(第三版)
- Deep Learning for Natural Language Processing
- 軟件測試項目實戰(zhàn)之功能測試篇
- 計算機信息技術實踐教程
- Delphi Cookbook
- RPA開發(fā):UiPath入門與實戰(zhàn)