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

Static factory

Let's write a simple factory to create instances of vehicles. We have an abstract Vehicle class and three concrete classes inherited from it: Bike, Car, and Truck. The factory, also called the static factory, will look like this:

public class VehicleFactory 
{
public enum VehicleType
{
Bike,Car,Truck
}
public static Vehicle create(VehicleType type)
{
if (type.equals(VehicleType.Bike))
return new Bike();
if (type.equals(VehicleType.Car))
return new Car();
if (type.equals(VehicleType.Truck))
return new Truck();
else return null;
}
}

The factory looks very simple and is responsible for the instantiation of the vehicle classes, complying with the single responsibility principle. It helps us to reduce coupling because the client depends only on the Vehicle interface, complying with the dependency inversion principle. If we need to add a new vehicle class, we need to change the VehicleFactory class, so the open/closed principle is broken.

We can improve the simple factory pattern to make it open for extension but closed for modification by using a mechanism to register new classes that will be instantiated when needed. There are two ways to achieve this:

  • Registering product class objects and instantiating them using reflection
  • Registering product objects and adding a newInstance method to each product that returns a new instance of the same class as itself
主站蜘蛛池模板: 麻江县| 锦州市| 都昌县| 蒙山县| 天峨县| 那曲县| 枣阳市| 九寨沟县| 醴陵市| 张家港市| 嘉荫县| 米林县| 安阳县| 沙湾县| 临桂县| 尚义县| 沅江市| 康保县| 江城| 谢通门县| 安图县| 永福县| 易门县| 侯马市| 新乡县| 长沙县| 隆子县| 天祝| 红原县| 万全县| 娱乐| 义乌市| 石台县| 荆州市| 临武县| 于都县| 汤阴县| 西乌珠穆沁旗| 广南县| 广宁县| 鹤庆县|