Java – understanding abstract factory patterns

I've read about the abstract factory pattern on the wiki But I don't understand that using this model is really profitable Can you get an example where it's hard to avoid abstract factory patterns? 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 need to create objects less than 1-2 times in the code, we can only use the new operator Why do we need Abstract factories?

Solution

You missed half your job:)

void processOrder(FinancialToolsFactory ftf,Order o) {

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

This code is as valid as the Canadian or European implementation you passed to financialtoolsfactory (you can externalize the implementer class as an external resource and instantiate it with class. Newinstance())

In this case, one of the real benefits of using patterns is not writing the code that implements the pattern, but the code that uses it!

PS: my answer is deliberately incomplete. Try to answer this specific question; There is too much discussion about patterns and their benefits!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>