Liskov Substitution Principle and Abstract Factories

From: Jimmy Cerra (jfcst24_public_at_yahoo.com)
Date: 01/09/05


Date: Sun, 09 Jan 2005 04:42:50 GMT

Does the intent of the Abstract Factory Pattern conflict with the Liskov
Substitution Principle (LSP)?

According to GoF [1], an Abstract Factory is intended to "provide an
interface for creating families of related or dependent objects without
specifying their concrete classes." I think I understand the mechanics
of the pattern well.

The conventional example uses different GUI toolkits, like a Motif
look-and-feel vs. a Presentation Manager look-and-feel. The client uses
a factory to make a widget from a particular look-and-feel. E.G.

Factory fact = MotifFactory.getInstance();
Window ww = fact.createWindow();
Button bb = fact.createButton();
ww.add(bb);

It is easy to change the application's appearence. Simply replace
MotifFactory with another factory (say, PMFactory).

Factory fact = PMFactory.getInstance();
Window ww = fact.createWindow();
Button bb = fact.createButton();
ww.add(bb);

The objects created by MotifFactory are highly coupled since they each
expect a particular look-and-feel. Mixing them with PMFactory objects
would conflict with that style. In fact, that's the whole point of
using the Abstract Factory Pattern - making it easy to use lots of
dependent classes. So it wouldn't make sense to mix the two toolkits. E.G.

Factory mf = MotifFactory.getInstance();
Factory pmf = PMFactory.getInstance();
Window ww = mf.createWindow();
Button bb = pmf.createButton();
ww.add(bb);

However, the objects created by each factory are each derived from the
same interfaces. E.G. Both MotifWindow aand PMWindow extend the Window
interface. So the LSP suggests that this usage should still be valid,
doesn't it [2]? In general, I don't think it would even produce a
compiler error.

So how does one reconsile these conflicting ideas? The LSP suggests
that the Motif and PM objects should be exchangable, but that doesn't
make sense in this case. Is there a design flaw?

--
Jimmy Cerra
https://nemo.dev.java.net
[1] Design Patterns, ISBN 0-201-63361-2
[2] http://c2.com/cgi/wiki?LiskovSubstitutionPrinciple

Quantcast