5

I have to create an object X using properties of object Y (both are of same type) in 4-5 different ways i.e. depending upon situation, those properties of Y can be used to initialize X in different ways. One way to do is , create an object X using default constructor and then set its properties, but it has a disadvantage that if some problem occurs then we have an object in inconsistent state. Another way to do is create different constructors for all the cases with dummy parameters, which sounds really bad. Is there any good design pattern i can use here ?

5 Answers 5

6

If both objects are of the same type, you can use factory methods:

public class Foo {
    ...
    public Foo withBar(...) {
        Foo f = new Foo(this.param);
        f.setBar(...);
        return f;
    }

    public Foo withBaz(...) {
        Foo f = new Foo(this.param);
        f.setBaz(...);
        return f;
    }
}
...
Foo y = ...;
Foo x = y.withBar(...);

If types are different, you can make factory methods static and pass Y as a parameter.

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

1 Comment

Is it good practice to pass Y (different type) as a parameter to a constructor of X? Etc., public Foo(Bar y) { ... }
3

Sounds like you could use a slightly-specialized version of the Factory Pattern. E.g. Part of building an object could be to pass in an existing instance (or interface to an instance) to initialize a new object.

4 Comments

+1 additionally using a "factory method" would be satisfying for this case
@user625146: Agreed. I brought up the Pattern instead of the method because I thought it might help kcr's architecture.
In factory pattern, when to use them as static and when not ?
The factory method doesn't really fit the use of static classes. They are more about instances. I think in your case you are using multiple objects with different states I would suggest staying away from trying to do anything with static members.
2

Nice explanation for Factory Pattern can be found here.
Also Joshua Bloch is his book Effective Java suggests some good advantages of using static factories

Comments

0

This sounds like a case for the Abstract Factory pattern.

Comments

0

In addition to Factory Pattern, take a look at the Builder Pattern. This pattern allows the client to configure how an object is constructed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.