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

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");
主站蜘蛛池模板: 定陶县| 长乐市| 五指山市| 司法| 金湖县| 杭州市| 太原市| 青河县| 阿合奇县| 赫章县| 华蓥市| 保康县| 达孜县| 曲松县| 梁山县| 商南县| 高邑县| 无锡市| 延长县| 霍林郭勒市| 尖扎县| 成安县| 宾阳县| 吉首市| 新闻| 栾川县| 通城县| 攀枝花市| 刚察县| 鹿泉市| 黄骅市| 永城市| 建始县| 徐汇区| 依兰县| 台东市| 页游| 柘城县| 永春县| 鞍山市| 哈巴河县|