Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design pattern for creating an object from another object in different ways

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 ?

like image 704
r15habh Avatar asked Dec 21 '22 14:12

r15habh


2 Answers

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.

like image 148
axtavt Avatar answered Dec 28 '22 07:12

axtavt


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.

like image 33
Paul Sasik Avatar answered Dec 28 '22 07:12

Paul Sasik