Factory or Inheritance for Initialisation?
- From: "kognition@xxxxxxxxx" <kognition@xxxxxxxxx>
- Date: 5 Feb 2006 22:53:27 -0800
Through refinement of a design, a class inheritance tree has been
reduced to a single class that uses composition. I originally had
class Foo that knows to set the base MaxCount field to a specific
number. Class Bar doesnt need the MaxCount, so it must set the base
MaxCount to Infinity. Classes looked like:
+----------+
| FooBar |
+----------+
| MaxCount |
+----------+
^
|
|--------------+
| |
+----------+ +----------+
| Foo | | Bar |
+----------+ +----------+
Now, the logic that was overridden by the two subclasses has been
pulled out:
+----------+
| FooBar | +----------------+
+----------+------>| FooBarStrategy |
| MaxCount | 1 +----------------+
+----------+
Problem is MaxCount needs to be set for the two types Foo Bar. At
application initialization time, I need two FooBar classes setting up,
one for the Foo instance and one for the Bar instance that existed in
the first diagram. A classes uses the two FooBar classes:
+-------------+ +-------------+
| :SomeClient |-------| :Foo:FooBar |
| ----------- | | ----------- |
+-------------+ +-------------+
|
| +-------------+
+------------| :Bar:FooBar |
| ----------- |
+-------------+
When an instance of FooBar is created that represents the original Foo
instance, MaxCount must be set to 100. When FooBar for a Bar instance
is ceated, MaxCount must be set to Infinity, or UNLIMITED. A colleague
suggested I put the Foo and Bar classes back, and they initialise the
base FooBar during construction:
FooBar fooInstance = new Foo(new Foo_FooBarStrategy());
FooBar barInstance = new Bar(new Bar_FooBarStrategy());
Inside Foo (C#):
public class Foo {
public Foo()
: base(100) {}
}
public class Bar {
public Bar()
: base(UNLIMITED) {}
}
The other approach is to use a factory:
FooBar foo = factory.CreateFoo();
FooBar bar = factory.CreateBar();
public class Factory {
public Foo CreateFoo() {
return new FooBar(100, new Foo_FooBarStrategy());
}
public Bar CreateBar() {
return new FooBar(UNLIMITED, new Bar_FooBarStrategy());
}
}
The reason for pulling out the inheritance tree was that there was lots
of overriding going on that was confusing to read and understand. We
pulled the logic out quite nicely and have a design that is much more
expressive, but it leave us with the question, how do we set up the two
core types Foo and Bar?
Thanks.
k.
.
- Follow-Ups:
- Re: Factory or Inheritance for Initialisation?
- From: H. S. Lahman
- Re: Factory or Inheritance for Initialisation?
- From: Daniel T.
- Re: Factory or Inheritance for Initialisation?
- From: Tim Haugton
- Re: Factory or Inheritance for Initialisation?
- Prev by Date: Re: Simple inheritence question
- Next by Date: Re: Factory or Inheritance for Initialisation?
- Previous by thread: UML - Statecharts using Rhapsody
- Next by thread: Re: Factory or Inheritance for Initialisation?
- Index(es):
Relevant Pages
|