Understanding the Abstract Factory Pattern

I read about the abstract factory patter on the wiki . But I do not really understand the profit using this template. Can you give an example in which it is difficult to avoid the abstract factory pattern. Consider the following Java code:

public abstract class FinancialToolsFactory {
    public abstract TaxProcessor createTaxProcessor();
    public abstract ShipFeeProcessor createShipFeeProcessor();
}

public abstract class ShipFeeProcessor {
    abstract void calculateShipFee(Order order);
}

public abstract class TaxProcessor {
    abstract void calculateTaxes(Order order);
}

// Factories
public class CanadaFinancialToolsFactory extends FinancialToolsFactory {
    public TaxProcessor createTaxProcessor() {
        return new CanadaTaxProcessor();
    }
    public ShipFeeProcessor createShipFeeProcessor() {
        return new CanadaShipFeeProcessor();
    }
}

public class EuropeFinancialToolsFactory extends FinancialToolsFactory {
   public TaxProcessor createTaxProcessor() {
        return new EuropeTaxProcessor();
    }
    public ShipFeeProcessor createShipFeeProcessor() {
        return new EuropeShipFeeProcessor();
    }
}

// Products
public class EuropeShipFeeProcessor extends ShipFeeProcessor {
    public void calculateShipFee(Order order) {
        // insert here Europe specific ship fee calculation
    }
}   

public class CanadaShipFeeProcessor extends ShipFeeProcessor {
    public void calculateShipFee(Order order) {
        // insert here Canada specific ship fee calculation
    }
}

public class EuropeTaxProcessor extends TaxProcessor {
    public void calculateTaxes(Order order) {
        // insert here Europe specific tax calculation
    }
}

public class CanadaTaxProcessor extends TaxProcessor {
    public void calculateTaxes(Order order) {
        // insert here Canada specific tax calculation
    }
}

If we just need to create objects in the code below 1-2 times in the code, we can only use the new operator. And why do we need an abstract factory?

+3
source share
3 answers

You are missing half the work :)

void processOrder(FinancialToolsFactory ftf,Order o) {

  tft.createTaxProcessor().calculateTaxes(o);
  tft.createShipFeeProcessor().calculateShipFee(o);
}

, FinancialToolsFactory ( - , , Class.newInstance()).

- , , !

PS: ; !

+2

, . , factory, , (a.k.a.).

factory , , .

, , . , , , , .

+3

, , , "" .

, :

-, , , . new factory, factory .

: , new ConcreteClass(), new OtherConcreteClass(), . factory, , factory, OtherConcreteClass ( , ...)

+2

All Articles