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

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");
主站蜘蛛池模板: 太和县| 象州县| 礼泉县| 保靖县| 社旗县| 新密市| 泌阳县| 寿宁县| 南丰县| 泗洪县| 苍梧县| 阳江市| 肇庆市| 长兴县| 五大连池市| 南澳县| 中超| 平乡县| 眉山市| 宜丰县| 格尔木市| 宾川县| 金寨县| 和硕县| 习水县| 葫芦岛市| 金昌市| 昭苏县| 西安市| 茶陵县| 阆中市| 策勒县| 北宁市| 昭觉县| 两当县| 江山市| 分宜县| 元阳县| 韶山市| 宜丰县| 南溪县|