Reputation: 3328
I want to implement the abstract factory pattern. I have three classes
What I've done so far is implementing the abstract factory design pattern for the superclass. I have not handeled the inheritence yet. I do not know how to implement the pattern with the two subclasses. What do I need to add?
AbstractFactory
public abstract class AbstractFactory {
public abstract SC createNewSC();
}
SCConcreteFactory
public class SCConcreteFactory extends AbstractFactory {
@Override
public SC createNewSC() {
return new SC();
}
}
AbstractSC
public abstract class AbstractSC{
public abstract void doStuff();
}
SC
public class SC extends AbstractSC{
@Override
public void doStuff() {
System.out.println("Hello World");
}
}
Upvotes: 1
Views: 309
Reputation: 1697
You need to implement two factories for ChildA and ChildB respectively, for example:
public class ChildAFactory extends AbstractFactory {
@Override
public SC createNewSC() {
return new ChildA();
}
}
public class ChildBFactory extends AbstractFactory {
@Override
public SC createNewSC() {
return new ChildB();
}
}
Upvotes: 1
Reputation: 1701
one very detailed way to create abstract factories with inheritance is explained in this post: http://www.oodesign.com/abstract-factory-pattern.html
If your SC superclass is also abstract, you could easily take this:
public abstract class AbstractFactory {
public abstract SC sc();
}
public class ChildAFactory extends AbstractFactory {
public SC sc(){ return new ChildA();}
}
public class ChildBFactory extends AbstractFactory {
public SC sc(){ return new ChildB();}
}
And like written in the above mentioned article:
class FactoryMaker{
private static AbstractFactory pf=null;
static AbstractFactory getFactory(String choice){
if(choice.equals("a")){
pf=new ChildAFactory();
}else if(choice.equals("b")){
pf=new ChildBFactory();
} return pf;
}
}
// Client
public class Client{
public static void main(String args[]){
AbstractFactory pf= FactoryMaker.getFactory("a");
SC sc = pf.sc(); // ChildA is initialized
}
}
There are several ways to use the abstract factory - it depends on your requirements. This is a very simple approach and might change with your requirements. E.g., the solution above only tries to hide the concrete implementation. The client only knows SC.
HTH, Sabine
Upvotes: 1