membersound
membersound

Reputation: 86777

Use builder pattern with JSF?

I'm just trying to port a tiny desktop app of mine to web. Since days I'm trying to find out how I can make use of the builder pattern (I already have) in JSF? Or do I have to refactor to Bean Entities and cannot use Builder?

Consider following code:

public class MyFacade {
  private MyClass bar;

  publich save() {
    crudService.persist(bar);
  }
}


<h:inputText id="name" value="#{MyFacade.bar.property}" />
//submit button

I want so store text field values to my DB / entities of course. Which is quite easy if you have normal backend beans.

But what if I create my objects like the following?

MyClass newObject = MyClass.Builder("mandatory field").setOptionalFields("optional field").build();

How can I make use of this in jsf, if at all?

Thanks lot

Upvotes: 1

Views: 626

Answers (1)

Kris
Kris

Reputation: 5792

If I understand you correctly you should introduce another type of beans into your JSF application just for interaction with your view and leave your facade (dao) beans as they are. You would end up with something like this:

@RequestScoped
public class YourBean{

    @Inject
    private MyFacade facade;

    //bean created with builder
    private MyBean bean;

    public String someMethodExecutedwithEL(){
        //build your object here and save it with the dao layer
        facade.save(objectFromBuilder);
    }
    @PostConstruct
    public void init(){
        //create your bean with builder pattern
    }
}

Example above is of course just a scribbled idea, the point is that there is nothing stopping you from creating your objects using builder pattern, just introduce another layer for separation of concerns.

EDIT:

If you want to create your objects before they are used on the jsf page you can add method annotated @PostConstruct (updated the code sample as well)

Possibilities are endless.

Tip - consider naming your classes and variables using standard naming conventions and common sense.

Upvotes: 1

Related Questions