1

I have read Factory Method pattern. I have a problem when design the latter example.

Best design for the pattern? Anybody can give me any suggestions?

 AbstractProduct Creator / \ / \ Product1 Product2 Creator1 Creator2 AbstractProduct ? How to design Creator ? / | \ Product1 Product2 SubAbstractProduct / \ Product3 Product 4 

1 Answer 1

1

Creator can be designed the same way as in the previous example because Concrete Creators that create Product3 and Product4 still are AbstractProduct.

Answering the comment:

Not really. When this AbstractProduct createProduct() is overridden in child Concrete Creator classes (which is the factory pattern), it can return SubAbstractProduct.

Just wanted to add that you can do the above (i.e. overridden method returning a subtype of what is returned in the parent class method)in java since Java 1.5.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. But if Creator have a method: AbstractProduct createProduct(), then when I use product = createProduct() so product is just AbstractProduct type, not SubAbstractProduct, product can't use any extended method from SubAbstractProduct.
OK, but if SubAbstractProduct has a method that AbstractProduct hasn't, moreMethod() for example. While product is just AbstractProduct, so if it want to use moreMethod(), I have to type cast.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.