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

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

+4
source share
5 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 the types are different, you can make factory static methods and pass Y as a parameter.

+5
source

It looks like you could use a slightly specialized version of Factory Pattern . For instance. Part of creating an object may be to transfer to an existing instance (or interface to the instance) to initialize a new object.

+3
source

A good explanation for the Factory Template can be found here .
Also Joshua Bloch - his book Effective Java offers some good benefits of using static factories.

+2
source

In addition to the Factory pattern, take a look at the Builder Pattern . This template allows the client to customize the way the object is built.

0
source

This is similar to the Abstract Factory case.

0
source

All Articles