Friday, June 4, 2010

Factory pattern

Factory Pattern - a type of Creational Pattern. The creational patterns deal with the best way to create instances of objects.

Sample design

 public interface IEquipment {
String getType();
}

public abstract class Equipment implements IEquipment{
public String getNumber() {
return number;
}
protected void setNumber(String number) {
this.number = number;
}
private String number;
}


public class Container extends Equipment{
public Boolean getIsReefer() {
return isReefer;
}
protected void setIsReefer(Boolean isReefer) {
this.isReefer = isReefer;
}
public String getType() {
return "Container";
}

private Boolean isReefer;
}


public class Chassis extends Equipment {
public Boolean getIsWheeled() {
return isWheeled;
}
protected void setWheeled(Boolean isWheeled) {
this.isWheeled = isWheeled;
}
public String getType() {
return "Chassis";
}

private Boolean isWheeled;
}


public class Accessory extends Equipment {
public String getDescription() {
return description;
}
protected void setDescription(String description) {
this.description = description;
}
public String getType() {
return "Accessory";
}

private String description;
}


// Factory producing Equipments
public class EquipmentFactory {
public static IEquipment createEquipment(String inEquipmentType) {
IEquipment equipment = null;
if (CONTAINER.equals(inEquipmentType)) {
equipment = new Container();
} else if (CHASSIS.equals(inEquipmentType)) {
equipment = new Chassis();
} else if (ACCESSORY.equals(inEquipmentType)) {
equipment = new Accessory();
}
return equipment;
}

private static final String CONTAINER = Container.class.getName();
private static final String CHASSIS = Chassis.class.getName();
private static final String ACCESSORY = Accessory.class.getName();
}

No comments: