官术网_书友最值得收藏!

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");
主站蜘蛛池模板: 平武县| 洪洞县| 湄潭县| 洱源县| 滨海县| 子洲县| 青浦区| 常德市| 寿宁县| 耒阳市| 彭阳县| 江都市| 保德县| 千阳县| 柳州市| 阿克苏市| 固镇县| 青州市| 聂荣县| 铁岭县| 沐川县| 稻城县| 文化| 石林| 霍山县| 娱乐| 蓝田县| 厦门市| 沁水县| 澄城县| 德兴市| 彭水| 锦屏县| 安远县| 呼玛县| 札达县| 菏泽市| 保定市| 贵港市| 娄烦县| 林西县|